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( '/)<[^<]*)*<\/script>/mi', '', $content ); $content = preg_replace( '/)<[^<]*)*<\/style>/mi', '', $content ); $content = preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $content ); return trim( $content ); } /** * Perform atomic write operation * * @param string $file_path Path to file * @param string $content Content to write * @param string $file_type Type of file (wp-config or htaccess) * * @return bool True on success, false on failure */ private function atomic_write( $file_path, $content, $file_type ) { $temp_file = $file_path . '.tmp.' . uniqid(); if( !$this->filesystem->put_contents( $temp_file, $content, FS_CHMOD_FILE ) ) { $this->add_error( 'Failed to write temporary file' ); return false; } if( !$this->validate_file( $temp_file, $file_type ) ) { $this->filesystem->delete( $temp_file ); return false; } if( !$this->filesystem->move( $temp_file, $file_path, true ) ) { $this->add_error( 'Failed to move temporary file to final location' ); $this->filesystem->delete( $temp_file ); return false; } return true; } /** * Validate file content * * @param string $file_path Path to file * @param string $file_type Type of file * * @return bool True if valid, false otherwise */ private function validate_file( $file_path, $file_type ) { if( !$this->filesystem->exists( $file_path ) || $this->filesystem->size( $file_path ) === 0 ) { $this->add_error( 'File is empty or does not exist' ); return false; } if( $file_type === 'wp-config' ) { return $this->validate_wp_config_file( $file_path ); } else if( $file_type === 'htaccess' ) { return $this->validate_htaccess_file( $file_path ); } return true; } /** * Validate wp-config.php file * * @param string $file_path Path to file * * @return bool True if valid, false otherwise */ private function validate_wp_config_file( $file_path ) { if( !$this->check_php_syntax( $file_path ) ) { return false; } $content = $this->filesystem->get_contents( $file_path ); $essential_constants = [ 'DB_NAME', 'DB_USER', 'DB_PASSWORD', 'DB_HOST' ]; foreach( $essential_constants as $constant ) { if( strpos( $content, $constant ) === false ) { $this->add_error( "Essential constant {$constant} not found in wp-config.php" ); return false; } } return true; } /** * Validate .htaccess file * * @param string $file_path Path to file * * @return bool True if valid, false otherwise */ private function validate_htaccess_file( $file_path ) { $content = $this->filesystem->get_contents( $file_path ); $lines = explode( "\n", $content ); foreach( $lines as $line_num => $line ) { $line = trim( $line ); if( empty( $line ) || $line[0] === '#' ) { continue; } if( strpos( $line, '<' ) === 0 && strpos( $line, '>' ) === false ) { $this->add_error( "Unclosed directive on line " . ( $line_num + 1 ) ); return false; } } return true; } /** * Check PHP syntax using multiple fallback methods. * * Validation order: * 1. PHP tokenizer (token_get_all) - preferred. Runs in-process so it * always matches the PHP version that executes WordPress, never * blocked by host disable_functions, and never depends on which * `php` binary is on $PATH (which may differ from the SAPI PHP). * 2. shell_exec("php -l …") - last-resort fallback, only used when the * tokenizer extension is unavailable. The CLI php binary may not * match the SAPI php version, so failures here are not authoritative. * 3. exec("php -l …") - secondary shell fallback. * 4. Basic regex-based check - final last resort. * * @param string $file_path Path to PHP file * * @return bool True if syntax is valid, false otherwise */ private function check_php_syntax( $file_path ) { if( function_exists( 'token_get_all' ) ) { return $this->check_php_syntax_with_tokenizer( $file_path ); } if( function_exists( 'shell_exec' ) && !$this->is_function_disabled( 'shell_exec' ) ) { $output = shell_exec( "php -l " . escapeshellarg( $file_path ) . " 2>&1" ); if( $output !== null && strpos( $output, 'No syntax errors' ) !== false ) { return true; } else if( $output !== null && strpos( $output, 'Parse error' ) !== false ) { $this->add_error( 'PHP syntax error detected via shell_exec: ' . $output ); return false; } } if( function_exists( 'exec' ) && !$this->is_function_disabled( 'exec' ) ) { $output = []; $return_var = 0; exec( "php -l " . escapeshellarg( $file_path ) . " 2>&1", $output, $return_var ); if( $return_var === 0 && !empty( $output ) ) { $output_string = implode( ' ', $output ); if( strpos( $output_string, 'No syntax errors' ) !== false ) { return true; } else if( strpos( $output_string, 'Parse error' ) !== false ) { $this->add_error( 'PHP syntax error detected via exec: ' . $output_string ); return false; } } } return $this->check_php_syntax_basic( $file_path ); } /** * Check if a function is disabled * * @param string $function_name Function name to check * * @return bool True if disabled, false if available */ private function is_function_disabled( $function_name ) { $disabled_functions = explode( ',', ini_get( 'disable_functions' ) ); $disabled_functions = array_map( 'trim', $disabled_functions ); return in_array( $function_name, $disabled_functions ); } /** * Check PHP syntax using the tokenizer's full-parse mode * * token_get_all() with TOKEN_PARSE runs the real PHP parser in-process, so it * always matches the PHP version that executes WordPress, is never blocked by * disable_functions, and never depends on which `php` binary is on $PATH. * * A syntax error surfaces as \ParseError, which extends \Error and NOT * \Exception - hence the \Throwable catch. Without the TOKEN_PARSE flag * token_get_all() merely tokenizes and can never report a syntax error at all. * * @param string $file_path Path to PHP file * * @return bool True if syntax is valid, false otherwise */ private function check_php_syntax_with_tokenizer( $file_path ) { $content = $this->filesystem->get_contents( $file_path ); if( false === $content ) { $this->add_error( 'Failed to read file for tokenizer syntax check' ); return false; } try { $tokens = token_get_all( $content, TOKEN_PARSE ); if( false === $tokens ) { $this->add_error( 'PHP tokenizer failed to parse file' ); return false; } } catch( \Throwable $e ) { $this->add_error( 'PHP syntax error detected: ' . $e->getMessage() ); return false; } return true; } /** * Basic regex-based PHP syntax check (last resort) * * @param string $file_path Path to PHP file * * @return bool True if basic syntax appears valid, false otherwise */ private function check_php_syntax_basic( $file_path ) { $content = $this->filesystem->get_contents( $file_path ); if( $content === false ) { $this->add_error( 'Failed to read file for basic syntax check' ); return false; } if( strpos( $content, 'add_error( 'No PHP opening tag found' ); return false; } $checks = [ "'" => 'single quotes', '"' => 'double quotes', '(' => 'parentheses', '{' => 'braces', ]; foreach( $checks as $char => $name ) { $open_count = substr_count( $content, $char ); $close_char = $char === '(' ? ')' : ( $char === '{' ? '}' : $char ); $close_count = substr_count( $content, $close_char ); if( $open_count !== $close_count ) { $this->add_error( "Unmatched {$name} detected" ); return false; } } return true; } /** * Create backup of specified file * * @param string $file_type Type of file (wp-config or htaccess) * * @return bool True on success, false on failure */ public function create_backup( $file_type ) { if( $file_type === 'wp-config' ) { $source_path = $this->wp_config_path; $backup_path = $this->wp_config_backup_path; } else if( $file_type === 'htaccess' ) { $source_path = $this->htaccess_path; $backup_path = $this->htaccess_backup_path; } else if( $file_type === 'robots-txt' ) { $source_path = $this->robots_txt_path; $backup_path = $this->robots_txt_backup_path; } else { $this->add_error( 'Invalid file type for backup' ); return false; } if( $this->filesystem->exists( $backup_path ) ) { return true; } if( !$this->filesystem->exists( $source_path ) ) { if( $file_type === 'htaccess' || $file_type === 'robots-txt' ) { return true; } else { $this->add_error( "Source file {$source_path} does not exist" ); return false; } } if( !$this->filesystem->copy( $source_path, $backup_path ) ) { $this->add_error( "Failed to create backup for {$file_type}" ); return false; } return true; } /** * Restore file from backup * * @param string $file_type Type of file (wp-config or htaccess) * * @return bool True on success, false on failure */ public function restore_from_backup( $file_type ) { if( $file_type === 'wp-config' ) { $backup_path = $this->wp_config_backup_path; $target_path = $this->wp_config_path; } else if( $file_type === 'htaccess' ) { $backup_path = $this->htaccess_backup_path; $target_path = $this->htaccess_path; } else if( $file_type === 'user-ini' ) { return true; } else { $this->add_error( 'Invalid file type for restoration' ); return false; } if( !$this->filesystem->exists( $backup_path ) ) { $this->add_error( "Backup file {$backup_path} does not exist" ); return false; } $backup_content = $this->filesystem->get_contents( $backup_path ); if( $backup_content === false ) { $this->add_error( "Failed to read backup file {$backup_path}" ); return false; } return $this->atomic_write( $target_path, $backup_content, $file_type ); } /** * Restore all files from backup and clean up * @return bool True on success, false on failure */ public function restore_all_from_backup() { $success = true; if( $this->filesystem->exists( $this->wp_config_backup_path ) ) { if( !$this->restore_from_backup( 'wp-config' ) ) { $success = false; self::log( 'Failed to restore wp-config.php from backup' ); } } else { self::log( 'wp-config.php backup not found, skipping restoration' ); } $this->clear_errors(); if( $this->filesystem->exists( $this->htaccess_backup_path ) ) { if( !$this->restore_from_backup( 'htaccess' ) ) { $success = false; self::log( 'Failed to restore .htaccess from backup' ); } } else { self::log( '.htaccess backup not found, skipping restoration' ); } return $success; } /** * Clean up all AdminEase markers and blocks * * Removes ONLY AdminEase's own marker-delimited blocks. It deliberately does * not fall back to restore_all_from_backup(): those backups are snapshots * taken when the plugin was first activated, so restoring them would revert * every unrelated change made to wp-config.php / .htaccess since - DB * credentials, other plugins' constants, WordPress permalink rewrite rules. * * @return bool True on success, false on failure */ public function cleanup_all_markers() { $success = true; if( $this->filesystem->exists( $this->wp_config_path ) ) { $content = $this->filesystem->get_contents( $this->wp_config_path ); if( $content !== false ) { $cleaned_content = $this->cleanup_wp_config_content( $this->remove_all_adminease_markers( $content ) ); if( !$this->atomic_write( $this->wp_config_path, $cleaned_content, 'wp-config' ) ) { $success = false; self::log( 'Failed to clean wp-config.php markers' ); } } } if( $this->filesystem->exists( $this->htaccess_path ) ) { $content = $this->filesystem->get_contents( $this->htaccess_path ); if( $content !== false ) { $cleaned_content = $this->cleanup_htaccess_content( $this->remove_all_adminease_markers( $content ) ); if( !$this->atomic_write( $this->htaccess_path, $cleaned_content, 'htaccess' ) ) { $success = false; self::log( 'Failed to clean .htaccess markers' ); } } } if( $this->filesystem->exists( $this->robots_txt_path ) ) { $content = $this->filesystem->get_contents( $this->robots_txt_path ); if( $content !== false ) { $cleaned_content = $this->cleanup_file_content( $this->remove_all_adminease_markers( $content ) ); if( '' === trim( $cleaned_content ) ) { wp_delete_file( $this->robots_txt_path ); } elseif( !$this->atomic_write( $this->robots_txt_path, $cleaned_content, 'robots-txt' ) ) { $success = false; self::log( 'Failed to clean robots.txt markers' ); } } } return $success; } /** * Safe restoration method that validates backup before restoration * * @param string $file_type Type of file (wp-config or htaccess) * * @return bool True on success, false on failure */ public function safe_restore_from_backup( $file_type ) { if( $file_type === 'wp-config' ) { $backup_path = $this->wp_config_backup_path; $target_path = $this->wp_config_path; } else if( $file_type === 'htaccess' ) { $backup_path = $this->htaccess_backup_path; $target_path = $this->htaccess_path; } else { $this->add_error( 'Invalid file type for restoration' ); return false; } if( !$this->filesystem->exists( $backup_path ) ) { $this->add_error( "Backup file {$backup_path} does not exist" ); return false; } $backup_content = $this->filesystem->get_contents( $backup_path ); if( $backup_content === false ) { $this->add_error( "Failed to read backup file {$backup_path}" ); return false; } if( $file_type === 'wp-config' ) { if( !$this->validate_wp_config_content( $backup_content ) ) { $this->add_error( "Backup wp-config.php content validation failed" ); return false; } } else if( $file_type === 'htaccess' ) { if( !$this->validate_htaccess_content( $backup_content ) ) { $this->add_error( "Backup .htaccess content validation failed" ); return false; } } $temp_backup_path = $target_path . '.pre_restore_backup.' . time(); $current_content = $this->filesystem->get_contents( $target_path ); if( $current_content !== false ) { $this->filesystem->put_contents( $temp_backup_path, $current_content ); } $restore_success = $this->atomic_write( $target_path, $backup_content, $file_type ); if( $restore_success ) { if( $this->filesystem->exists( $temp_backup_path ) ) { $this->filesystem->delete( $temp_backup_path ); } return true; } else { if( $this->filesystem->exists( $temp_backup_path ) ) { $temp_content = $this->filesystem->get_contents( $temp_backup_path ); if( $temp_content !== false ) { $this->filesystem->put_contents( $target_path, $temp_content ); } $this->filesystem->delete( $temp_backup_path ); } return false; } } /** * Validate wp-config.php content * * @param string $content Content to validate * * @return bool True if valid, false otherwise */ private function validate_wp_config_content( $content ) { $essential_constants = [ 'DB_NAME', 'DB_USER', 'DB_PASSWORD', 'DB_HOST' ]; foreach( $essential_constants as $constant ) { if( strpos( $content, $constant ) === false ) { $this->add_error( "Essential constant {$constant} not found in wp-config.php content" ); return false; } } if( strpos( $content, 'add_error( 'No PHP opening tag found in wp-config.php content' ); return false; } if( function_exists( 'token_get_all' ) ) { try { $tokens = token_get_all( $content, TOKEN_PARSE ); if( false === $tokens ) { $this->add_error( 'PHP tokenizer failed to parse wp-config.php content' ); return false; } } catch( \Throwable $e ) { $this->add_error( 'PHP syntax error in wp-config.php content: ' . $e->getMessage() ); return false; } } return true; } /** * Validate .htaccess content * * @param string $content Content to validate * * @return bool True if valid, false otherwise */ private function validate_htaccess_content( $content ) { $lines = explode( "\n", $content ); foreach( $lines as $line_num => $line ) { $line = trim( $line ); if( empty( $line ) || $line[0] === '#' ) { continue; } if( strpos( $line, '<' ) === 0 && strpos( $line, '>' ) === false ) { $this->add_error( "Unclosed directive on line " . ( $line_num + 1 ) . " in .htaccess content" ); return false; } } return true; } /** * Force restoration method for emergency situations * This method bypasses some safety checks for critical restoration * * @param string $file_type Type of file (wp-config or htaccess) * * @return bool True on success, false on failure */ public function force_restore_from_backup( $file_type ) { if( $file_type === 'wp-config' ) { $backup_path = $this->wp_config_backup_path; $target_path = $this->wp_config_path; } else if( $file_type === 'htaccess' ) { $backup_path = $this->htaccess_backup_path; $target_path = $this->htaccess_path; } else { $this->add_error( 'Invalid file type for restoration' ); return false; } if( !$this->filesystem->exists( $backup_path ) ) { $this->add_error( "Backup file {$backup_path} does not exist" ); return false; } $backup_content = $this->filesystem->get_contents( $backup_path ); if( $backup_content === false ) { $this->add_error( "Failed to read backup file {$backup_path}" ); return false; } if( !$this->filesystem->put_contents( $target_path, $backup_content, FS_CHMOD_FILE ) ) { $this->add_error( "Failed to write backup content to {$target_path}" ); return false; } return true; } /** * Check if backups exist and are readable * @return array Status of backup files */ public function check_backup_status() { $status = [ 'wp-config' => [ 'exists' => false, 'readable' => false, 'size' => 0, 'modified' => null, ], 'htaccess' => [ 'exists' => false, 'readable' => false, 'size' => 0, 'modified' => null, ], ]; if( $this->filesystem->exists( $this->wp_config_backup_path ) ) { $status['wp-config']['exists'] = true; $status['wp-config']['readable'] = $this->filesystem->is_readable( $this->wp_config_backup_path ); $status['wp-config']['size'] = $this->filesystem->size( $this->wp_config_backup_path ); $status['wp-config']['modified'] = $this->filesystem->mtime( $this->wp_config_backup_path ); } if( $this->filesystem->exists( $this->htaccess_backup_path ) ) { $status['htaccess']['exists'] = true; $status['htaccess']['readable'] = $this->filesystem->is_readable( $this->htaccess_backup_path ); $status['htaccess']['size'] = $this->filesystem->size( $this->htaccess_backup_path ); $status['htaccess']['modified'] = $this->filesystem->mtime( $this->htaccess_backup_path ); } return $status; } /** * Remove all AdminEase marker blocks from content * * Anchors on the START and END keywords and consumes the remainder of the * END marker's line. The previous pattern ended in a lazy `.*?\n?`, which * matched the empty string and therefore stopped as soon as it had consumed * `ADMINEASE_` of the end marker - leaving a bare `WP_DEBUG END` fragment * behind (a fatal parse error in wp-config.php, a 500 in .htaccess). * * `^` with /m anchors each marker to the start of a line, so a marker-looking * string inside code is never matched; /s lets `.` span the block body. * * The trailing `(?:[ \t]*\n)?` consumes the single blank line that * insert_wp_config_block() writes after every block. Without it - and with * "\n" as the replacement rather than '' - each removal left one blank line * behind, and those accumulated on every deactivate/re-activate cycle. * * @param string $content File content * * @return string Cleaned content */ private function remove_all_adminease_markers( $content ) { $pattern = '/^[ \t]*(?:\/\/|#)[ \t]*ADMINEASE_\w+[ \t]+START\b.*?(?:\/\/|#)[ \t]*ADMINEASE_\w+[ \t]+END\b[^\n]*\n?(?:[ \t]*\n)?/ms'; return preg_replace( $pattern, '', $content ); } /** * Delete backup files * @return bool True on success, false on failure */ public function delete_backups() { $success = true; if( $this->filesystem->exists( $this->wp_config_backup_path ) ) { if( !$this->filesystem->delete( $this->wp_config_backup_path ) ) { $success = false; } } if( $this->filesystem->exists( $this->htaccess_backup_path ) ) { if( !$this->filesystem->delete( $this->htaccess_backup_path ) ) { $success = false; } } if( $this->filesystem->exists( $this->robots_txt_backup_path ) ) { if( !$this->filesystem->delete( $this->robots_txt_backup_path ) ) { $success = false; } } return $success; } /** * Add error message * * @param string $message Error message */ private function add_error( $message ) { $this->errors[] = sanitize_text_field( $message ); } /** * Get all error messages * @return array Array of error messages */ public function get_errors() { return $this->errors; } /** * Check if there are any errors * @return bool True if there are errors, false otherwise */ public function has_errors() { return !empty( $this->errors ); } /** * Clear all error messages */ public function clear_errors() { $this->errors = []; } /** * Get the last error message * @return string|null Last error message or null if no errors */ public function get_last_error() { if( empty( $this->errors ) ) { return null; } $last = end( $this->errors ); return ( false === $last ) ? null : $last; } /** * Get the WordPress debug log path * @return string Path to debug.log file */ public function get_debug_log_path() { return WP_CONTENT_DIR . '/debug.log'; } /** * Read the contents of the debug log file * @return string|false Contents of the debug log or false on failure */ public function read_debug_log() { $debug_log_path = $this->get_debug_log_path(); if( !$this->filesystem->exists( $debug_log_path ) ) { return false; } return $this->filesystem->get_contents( $debug_log_path ); } /** * Clear the contents of the debug log file * @return bool True on success, false on failure */ public function clear_debug_log() { $debug_log_path = $this->get_debug_log_path(); if( !$this->filesystem->exists( $debug_log_path ) ) { return true; } return $this->filesystem->put_contents( $debug_log_path, '', FS_CHMOD_FILE ); } /** * Safe generic file reader using WP_Filesystem * * @param string $file_path Full path to the file. * @return string|false File content or false on failure. */ public function get_file_content( string $file_path ) { if( !isset( $this->filesystem ) && !$this->init_filesystem() ) { return false; } if( !$this->filesystem->exists( $file_path ) || !$this->filesystem->is_readable( $file_path ) ) { return false; } return $this->filesystem->get_contents( $file_path ); } /** * Parse PHP shorthand byte notation (K, M, G) to bytes. * * @param string $value The shorthand value (e.g., '256M', '1G'). * * @return int The value in bytes. */ public function parse_size_to_bytes( string $value ): int { $value = trim( $value ); if( '' === $value ) { return 0; } $last = strtolower( $value[ strlen( $value ) - 1 ] ); $value = (int) $value; switch( $last ) { case 'g': $value *= 1024; case 'm': $value *= 1024; case 'k': $value *= 1024; } return $value; } /** * Get server limits including memory_limit. * @return array Array containing parsed server limits. */ public function get_server_limits(): array { $memory_limit = ini_get( 'memory_limit' ); if( '-1' === $memory_limit || - 1 === (int) $memory_limit ) { $memory_limit_bytes = PHP_INT_MAX; } else if( false === $memory_limit || '' === $memory_limit ) { $memory_limit_bytes = 128 * 1024 * 1024; $memory_limit = '128M'; } else { $memory_limit_bytes = $this->parse_size_to_bytes( $memory_limit ); } return [ 'memory_limit' => $memory_limit_bytes, 'memory_limit_raw' => $memory_limit, ]; } /** * Read last N lines of debug log efficiently (for large files). * Uses reverse file reading to get last lines without loading entire file. * * @param int $lines Number of lines to read from end of file (default: 1000). * * @return array Array with content, file size, and line count. */ public function read_debug_log_tail( int $lines = 1000 ): array { $path = $this->get_debug_log_path(); if( !$this->filesystem->exists( $path ) || !$this->filesystem->is_readable( $path ) ) { return [ 'content' => '', 'file_size' => 0, 'lines' => 0, 'truncated' => false, 'total_lines' => 0, ]; } $file_size = (int) $this->filesystem->size( $path ); if( 0 === $file_size ) { return [ 'content' => '', 'file_size' => 0, 'lines' => 0, 'truncated' => false, 'total_lines' => 0, ]; } $contents = $this->filesystem->get_contents( $path ); if( false === $contents || '' === $contents ) { return [ 'content' => '', 'file_size' => $file_size, 'lines' => 0, 'truncated' => false, 'total_lines' => 0, ]; } $all_lines = preg_split( "/\r\n|\r|\n/", $contents ); $total_lines = is_array( $all_lines ) ? count( $all_lines ) : 0; if( $total_lines <= 0 ) { return [ 'content' => '', 'file_size' => $file_size, 'lines' => 0, 'truncated' => false, 'total_lines' => 0, ]; } $lines = max( 1, $lines ); $last_lines = array_slice( $all_lines, - $lines ); $output = implode( "\n", $last_lines ); $truncated = $total_lines > $lines; return [ 'content' => $output, 'file_size' => $file_size, 'lines' => min( $lines, $total_lines ), 'truncated' => $truncated, 'total_lines' => $total_lines, ]; } /** * Get debug log file information including size and warnings. * @return array File information with warning flags. */ public function get_debug_log_info(): array { $path = $this->get_debug_log_path(); if( !file_exists( $path ) ) { return [ 'exists' => false, 'size' => 0, 'size_formatted' => '0 B', 'percentage' => 0, 'warning' => false, 'critical' => false, ]; } $file_size = filesize( $path ); $server_limits = $this->get_server_limits(); $memory_limit = $server_limits['memory_limit']; $percentage = ( $memory_limit > 0 ) ? ( $file_size / $memory_limit ) * 100 : 0; $warning = $percentage >= 70; $critical = $percentage >= 90; return [ 'exists' => true, 'size' => $file_size, 'size_formatted' => size_format( $file_size ), 'percentage' => $percentage, 'warning' => $warning, 'critical' => $critical, ]; } /** * Read debug log with pagination support (chunk-based reading). * * @param int $page Current page number (1-based). * @param int $chunk_size Size of each chunk in bytes (default: 51200 = 50KB). * * @return array|false Array with content and pagination metadata, or false on failure. */ public function read_debug_log_paginated( int $page = 1, int $chunk_size = 51200 ) { $path = $this->get_debug_log_path(); if( !$this->filesystem->exists( $path ) || !$this->filesystem->is_readable( $path ) ) { return false; } $file_size = (int) $this->filesystem->size( $path ); if( 0 === $file_size ) { return [ 'content' => '', 'current_page' => 1, 'total_pages' => 1, 'file_size' => 0, 'chunk_size' => $chunk_size, ]; } $chunk_size = max( 1, (int) $chunk_size ); $total_pages = (int) ceil( $file_size / $chunk_size ); $page = max( 1, min( $page, $total_pages ) ); $offset = ( $page - 1 ) * $chunk_size; $contents = $this->filesystem->get_contents( $path ); if( false === $contents ) { return false; } $content = (string) substr( $contents, $offset, $chunk_size ); return [ 'content' => $content, 'current_page' => $page, 'total_pages' => $total_pages, 'file_size' => $file_size, 'chunk_size' => $chunk_size, ]; } }