hooks(); } return self::$instance; } /** * Register hooks. */ private function hooks(): void { // The register_settings_ui method is called by the ModuleManager. add_action( 'wp_ajax_' . self::REBUILD_AJAX_ACTION, [ $this, 'handle_rebuild_request' ] ); add_filter( 'adpresso_adblocker_tab_sections', [ $this, 'add_section' ] ); add_filter( 'adpresso_adblocker_tab_options', [ $this, 'add_options' ] ); add_action( 'admin_enqueue_scripts', function( $hook_suffix ) { $tab = Params::get()->getKey( 'tab' ); if ( $tab !== 'adblocker' ) { return; } wp_enqueue_script( 'wp-a11y' ); wp_add_inline_script( 'adpresso-admin-main', $this->inline_js ); } ); add_action( 'admin_init', [ $this, 'maybe_notify_unconfigured' ] ); // A module switched on or off brings or drops its frontend scripts: the lookup table has to follow. add_action( 'updated_option', [ self::class, 'maybe_schedule_on_module_change' ], 10, 3 ); } /** * Schedules a rebuild when a settings save switches a module on or off. * * @param string $option Option name. * @param mixed $old_value Previous value. * @param mixed $value New value. * * @return void */ public static function maybe_schedule_on_module_change( string $option, mixed $old_value, mixed $value ): void { if ( ! str_starts_with( $option, Constants::OPTION_PREFIX . 'settings_' ) ) { return; } $old_value = is_array( $old_value ) ? $old_value : []; $value = is_array( $value ) ? $value : []; foreach ( array_unique( array_merge( array_keys( $old_value ), array_keys( $value ) ) ) as $key ) { if ( str_starts_with( (string) $key, 'enable_module_' ) && ! empty( $old_value[ $key ] ) !== ! empty( $value[ $key ] ) ) { self::schedule_rebuild_if_active(); return; } } } /** * Schedules a rebuild while the module is on (plugin updates, module switches, Pro license activation). * * @return void */ public static function schedule_rebuild_if_active(): void { if ( ModuleManager::is_active( 'asset_masking', Constants::OPTION_PREFIX . 'settings_adblocker' ) ) { self::schedule_rebuild(); } } /** * Warns in the persistent Notification Center when the module is enabled but was never configured. */ public function maybe_notify_unconfigured(): void { $slug = 'adpresso-asset-masking-not-configured'; if ( ! ModuleManager::is_active( $this->get_id() ) ) { Notification_Center::get()->resolve( $slug ); return; } $config = Settings::get_direct_option( self::CONFIG_OPTION_NAME, [] ); if ( ! empty( $config['folder_name'] ) && ! empty( $config['last_generated'] ) ) { Notification_Center::get()->resolve( $slug ); return; } NotificationManager::get()->register( $slug, sprintf( /* translators: %1$s/%2$s wrap a link to the Adblocker settings tab. */ __( 'Asset Masking is enabled but not yet configured - your ads aren\'t hidden from ad blockers until you %1$srebuild the asset folder%2$s.', 'adpresso' ), '', '' ), [ 'type' => 'warning', 'location' => 'wp_notice', ] ); } /** * Adds a section to the Adblocker tab. * * @param $sections * * @return array */ public function add_section( $sections ): array { $sections['adblocker-asset-masking'] = [ 'title' => __( 'Asset Masking', 'adpresso' ), 'description' => '', 'controlled_by' => '', 'initially_open' => true, ]; return $sections; } /** * Adds options to the Adblocker tab. * * @param $options * * @return array */ public function add_options( $options ): array { $options[ 'enable_module_' . $this->get_id() ] = [ 'type' => 'toggle', 'label' => __( 'Enable Asset Masking', 'adpresso' ), 'description' => __( 'Hide your ads from ad blockers by serving plugin assets (CSS, JS) from a randomized, disguised folder within your uploads directory.', 'adpresso' ), 'default' => 0, 'section' => 'adblocker-asset-masking', 'highlighted' => true, ]; $options['asset-masking-status'] = [ 'type' => 'html-content', 'label' => __( 'Status', 'adpresso' ), 'description' => __( 'Asset Masking is not yet configured. Please rebuild the asset folder to complete the setup.', 'adpresso' ), 'html' => $this->render_status_field(), 'section' => 'adblocker-asset-masking', 'depends_on' => [ [ 'field_id' => 'enable_module_' . $this->get_id(), 'operator' => 'is', 'value' => 1, ], ], ]; $options['asset-masking-rebuild'] = [ 'type' => 'html-content', 'label' => __( 'Actions', 'adpresso' ), 'description' => __( 'Rebuild Asset Folder', 'adpresso' ), 'html' => $this->render_rebuild_button(), 'section' => 'adblocker-asset-masking', 'depends_on' => [ [ 'field_id' => 'enable_module_' . $this->get_id(), 'operator' => 'is', 'value' => 1, ], ], ]; return $options; } /** * Renders the status information for the Asset Masking feature. */ public function render_status_field(): string { $config = Settings::get_direct_option( self::CONFIG_OPTION_NAME, [] ); $folder_name = $config['folder_name'] ?? ''; $last_generated = $config['last_generated'] ?? 0; $output = ''; if ( ! $folder_name || ! $last_generated ) { $output .= '
' . esc_html__( 'Asset Masking is not yet configured. Please rebuild the asset folder.', 'adpresso' ) . '
'; return $output; } $upload_dir = wp_upload_dir(); $output .= '' . esc_html__( 'Current Asset Path', 'adpresso' ) . '
'; $output .= '' . esc_html( trailingslashit( $upload_dir['baseurl'] ) . $folder_name ) . '';
$output .= '' . sprintf( // translators: %s is a human-readable date. esc_html__( 'Last rebuilt on: %s', 'adpresso' ), esc_html( wp_date( get_option( 'date_format' ) . ' H:i:s', $last_generated ) ) ) . '
'; return $output; } /** * Renders the "Rebuild" button and the necessary JS for the AJAX call. */ public function render_rebuild_button(): string { ob_start(); ?> inline_js = " document.addEventListener( 'DOMContentLoaded', function () { const button = document.getElementById( 'adpresso-rebuild-assets-btn' ); const spinner = button.nextElementSibling; const feedback = document.getElementById( 'adpresso-rebuild-assets-feedback' ); const announce = function ( msg ) { if ( window.wp && wp.a11y && wp.a11y.speak ) { wp.a11y.speak( msg ); } }; // Re-shows the success message after the reload below, so it isn't lost. try { const saved = sessionStorage.getItem( 'adpresso_asset_masking_feedback' ); if ( saved ) { sessionStorage.removeItem( 'adpresso_asset_masking_feedback' ); const target = document.getElementById( 'adpresso-rebuild-assets-feedback' ); if ( target ) { target.style.display = 'block'; target.style.color = '#46b450'; target.textContent = saved; } announce( saved ); } } catch ( e ) {} button.addEventListener( 'click', function () { button.disabled = true; spinner.style.visibility = 'visible'; feedback.textContent = '" . esc_js( __( 'Rebuilding...', 'adpresso' ) ) . "'; feedback.style.color = ''; const data = new URLSearchParams(); data.append( 'action', '" . esc_js( self::REBUILD_AJAX_ACTION ) . "' ); data.append( '_ajax_nonce', '" . esc_js( wp_create_nonce( self::REBUILD_AJAX_ACTION ) ) . "' ); fetch( ajaxurl, { method: 'POST', body: data } ) .then( response => response.json() ) .then( result => { if ( result.success ) { feedback.textContent = result.data.message; feedback.style.color = '#46b450'; announce( result.data.message ); try { sessionStorage.setItem( 'adpresso_asset_masking_feedback', result.data.message ); } catch ( e ) {} // Reload the page to show the new status. setTimeout( () => window.location.reload(), 1500 ); } else { feedback.textContent = '" . esc_js( __( 'Error:', 'adpresso' ) ) . " ' + result.data.message; feedback.style.color = '#d63638'; announce( feedback.textContent ); } } ) .catch( error => { feedback.textContent = '" . esc_js( __( 'An unexpected error occurred.', 'adpresso' ) ) . "'; feedback.style.color = '#d63638'; announce( feedback.textContent ); console.error( 'Asset Rebuild Error:', error ); } ) .finally( () => { button.disabled = false; spinner.style.visibility = 'hidden'; } ); } ); } ); "; return ob_get_clean(); } /** * Handles the AJAX request to rebuild the disguised assets. */ public function handle_rebuild_request(): void { // Security checks check_ajax_referer( self::REBUILD_AJAX_ACTION ); if ( ! current_user_can( adpresso_get_capability( 'manage_settings' ) ) ) { wp_send_json_error( [ 'message' => __( 'Permission denied.', 'adpresso' ) ], 403 ); } // Same lock as the scheduled rebuild and purge, so none of them overwrites the other's config. if ( ! self::acquire_lock() ) { wp_send_json_error( [ 'message' => __( 'Another rebuild is running. Please try again in a few minutes.', 'adpresso' ) ], 409 ); return; } try { $result = $this->rebuild_assets(); } finally { self::release_lock(); } if ( is_wp_error( $result ) ) { wp_send_json_error( [ 'message' => $result->get_error_message() ], 500 ); } wp_send_json_success( [ 'message' => __( 'Asset folder rebuilt successfully!', 'adpresso' ) ] ); } /** * Marks the assets for a rebuild late in a request, once every asset is registered (used by plugin updates). * * @return void */ public static function schedule_rebuild(): void { $config = self::stored_config(); $config['rebuild_pending'] = true; update_option( Constants::OPTION_PREFIX . self::CONFIG_OPTION_NAME, $config, true ); } /** * Hooks a pending rebuild to wp_loaded: init has run by then, so every adpresso_register_assets listener exists. * * @return void */ public static function maybe_hook_scheduled_rebuild(): void { // Module check first: its option is read on every request anyway, the config option may not exist. if ( ! ModuleManager::is_active( 'asset_masking', Constants::OPTION_PREFIX . 'settings_adblocker' ) ) { return; } // Cached read on this hot path; the hooked callbacks re-check uncached under the lock. $config = get_option( Constants::OPTION_PREFIX . self::CONFIG_OPTION_NAME, [] ); $config = is_array( $config ) ? $config : []; if ( ! empty( $config['rebuild_pending'] ) ) { add_action( 'wp_loaded', [ self::class, 'run_scheduled_rebuild' ], 20 ); } elseif ( self::expired_folders( $config ) ) { add_action( 'wp_loaded', [ self::class, 'purge_expired_folders' ], 20 ); } } /** * Runs a scheduled rebuild, keeping the previous folder for cached pages. * * @return void */ public static function run_scheduled_rebuild(): void { if ( ! self::acquire_lock() ) { return; } try { $config = self::stored_config(); if ( empty( $config['rebuild_pending'] ) ) { return; } // Cleared first, so a failing rebuild is not retried on every request. unset( $config['rebuild_pending'] ); update_option( Constants::OPTION_PREFIX . self::CONFIG_OPTION_NAME, $config, true ); if ( ! ModuleManager::is_active( 'asset_masking', Constants::OPTION_PREFIX . 'settings_adblocker' ) ) { return; } $result = self::get_instance()->rebuild_assets( true ); if ( is_wp_error( $result ) ) { RuntimeDebugger::add_server_error_log_entry( 'Asset Disguise: scheduled rebuild failed: ' . $result->get_error_message() ); } } finally { self::release_lock(); } } /** * Deletes replaced folders whose grace period is over, without a rebuild. * * @return void */ public static function purge_expired_folders(): void { if ( ! self::acquire_lock() ) { return; } try { $config = self::stored_config(); $expired = self::expired_folders( $config ); if ( ! $expired ) { return; } $upload_dir = wp_upload_dir(); if ( ! empty( $upload_dir['error'] ) ) { return; } if ( ! self::init_filesystem() ) { return; } foreach ( $expired as $folder ) { self::delete_folder( trailingslashit( $upload_dir['basedir'] ), $folder ); } // Re-read: the config may have changed while deleting; only the purged entries are dropped. $config = self::stored_config(); foreach ( $expired as $folder ) { unset( $config['previous_folders'][ $folder ] ); } if ( empty( $config['previous_folders'] ) ) { unset( $config['previous_folders'] ); } update_option( Constants::OPTION_PREFIX . self::CONFIG_OPTION_NAME, $config, true ); } finally { self::release_lock(); } } /** * Uninstall: deletes the current and previous folders recorded in the config and forgets them. * * @return void */ public static function delete_recorded_folders(): void { $config = get_option( Constants::OPTION_PREFIX . self::CONFIG_OPTION_NAME, [] ); $folders = is_array( $config ) ? self::recorded_folders( $config ) : []; if ( ! $folders ) { return; } $upload_dir = wp_upload_dir(); if ( ! empty( $upload_dir['error'] ) ) { return; } if ( ! self::init_filesystem() ) { return; } foreach ( $folders as $folder ) { self::delete_folder( trailingslashit( $upload_dir['basedir'] ), $folder ); } // Kept data must not point at deleted folders; a reinstall rebuilds them. update_option( Constants::OPTION_PREFIX . self::CONFIG_OPTION_NAME, [ 'rebuild_pending' => true ], true ); } /** * Names of all folders a config records (current and previous). * * @param array $config Module config. * * @return string[] */ private static function recorded_folders( array $config ): array { $folders = is_array( $config['previous_folders'] ?? null ) ? array_map( 'strval', array_keys( $config['previous_folders'] ) ) : []; if ( ! empty( $config['folder_name'] ) && is_string( $config['folder_name'] ) ) { $folders[] = $config['folder_name']; } return array_values( array_unique( $folders ) ); } /** * Previous folders whose grace period is over. * * @param array $config Module config. * * @return string[] */ private static function expired_folders( array $config ): array { $previous = is_array( $config['previous_folders'] ?? null ) ? $config['previous_folders'] : []; $cutoff = time() - self::PREVIOUS_FOLDER_GRACE; return array_map( 'strval', array_keys( array_filter( $previous, static fn( $retired_at ) => (int) $retired_at < $cutoff ) ) ); } /** * Takes the lock with an atomic insert; only one concurrent request wins. A stale lock is taken over. * * @return bool */ private static function acquire_lock(): bool { global $wpdb; $name = Constants::OPTION_PREFIX . self::LOCK_OPTION_NAME; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Atomic lock, like WP_Upgrader::create_lock(). if ( $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO {$wpdb->options} (option_name, option_value, autoload) VALUES (%s, %s, 'no')", $name, (string) time() ) ) ) { return true; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Must bypass the option cache. $locked_at = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", $name ) ); if ( null !== $locked_at && (int) $locked_at > time() - self::LOCK_TIMEOUT ) { return false; } // Delete only the stale value read above, so a lock another request just took over survives. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching if ( null !== $locked_at && ! $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name = %s AND option_value = %s", $name, $locked_at ) ) ) { return false; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching return (bool) $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO {$wpdb->options} (option_name, option_value, autoload) VALUES (%s, %s, 'no')", $name, (string) time() ) ); } /** * Releases the lock. * * @return void */ private static function release_lock(): void { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $wpdb->delete( $wpdb->options, [ 'option_name' => Constants::OPTION_PREFIX . self::LOCK_OPTION_NAME ] ); } /** * The stored module config, read from the database: the autoloaded cache may predate another request's rebuild. * * @return array */ private static function stored_config(): array { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Must bypass the option cache. $raw = $wpdb->get_var( $wpdb->prepare( "SELECT option_value FROM {$wpdb->options} WHERE option_name = %s", Constants::OPTION_PREFIX . self::CONFIG_OPTION_NAME ) ); $config = null === $raw ? [] : maybe_unserialize( $raw ); return is_array( $config ) ? $config : []; } /** * Initializes WP_Filesystem if needed. * * @return bool Whether the filesystem is usable. */ private static function init_filesystem(): bool { global $wp_filesystem; if ( ! $wp_filesystem ) { require_once ABSPATH . 'wp-admin/includes/file.php'; WP_Filesystem(); } // Without direct access (FTP/SSH credentials needed) there is no filesystem object. return (bool) $wp_filesystem; } /** * Rebuilds the disguised assets. * * @param bool $keep_previous Keep the replaced folder for PREVIOUS_FOLDER_GRACE instead of deleting it right away. * * @return bool|\WP_Error True on success, WP_Error on failure. */ public function rebuild_assets( bool $keep_previous = false ) { $upload_dir = wp_upload_dir(); if ( ! empty( $upload_dir['error'] ) ) { return new \WP_Error( 'upload_dir_error', $upload_dir['error'] ); } $config = self::stored_config(); $old_folder = $config['folder_name'] ?? null; $base_dir = trailingslashit( $upload_dir['basedir'] ); if ( ! self::init_filesystem() ) { return new \WP_Error( 'filesystem_error', __( 'Could not access the file system.', 'adpresso' ) ); } global $wp_filesystem; // Create a new random directory $new_folder_name = 'adpr_assets_' . wp_generate_password( 8, false ); $new_folder_path = $base_dir . $new_folder_name; if ( ! $wp_filesystem->mkdir( $new_folder_path, FS_CHMOD_DIR ) ) { return new \WP_Error( 'mkdir_error', __( 'Could not create new asset directory.', 'adpresso' ) ); } $wp_filesystem->put_contents( trailingslashit( $new_folder_path ) . 'index.php', 'globals[ Assets::class ] ?? null; if ( ! $assets_service ) { $assets_service = new Assets(); $assets_service->hooks(); } $assets_to_mask = $assets_service->get_disguisable_assets(); foreach ( self::asset_variants( $assets_to_mask ) as $original_path ) { if ( ! $wp_filesystem->is_file( $original_path ) ) { continue; } // Generate new filename based on content hash $file_hash = substr( md5_file( $original_path ), 0, 10 ); $extension = pathinfo( $original_path, PATHINFO_EXTENSION ); $new_filename = $file_hash . '.' . $extension; // Copy the file $new_file_path = trailingslashit( $new_folder_path ) . $new_filename; if ( ! $wp_filesystem->copy( $original_path, $new_file_path, true, FS_CHMOD_FILE ) ) { RuntimeDebugger::add_server_error_log_entry( 'Asset Disguise: Failed to copy ' . $original_path ); continue; } // Map the original URL path to the new URL path $normalized_original = wp_normalize_path( $original_path ); $plugin_path = wp_normalize_path( plugin_dir_path( ADPRESSO_FILE ) ); $original_url_path = ltrim( str_replace( $plugin_path, '', $normalized_original ), '/' ); // Prefix with the plugin folder path as seen in URLs (e.g. wp-content/plugins/adpresso/) $plugin_url_path = wp_normalize_path( ltrim( wp_parse_url( plugin_dir_url( ADPRESSO_FILE ), PHP_URL_PATH ), '/' ) ); $original_url_path = $plugin_url_path . $original_url_path; $lookup_table[ $original_url_path ] = $new_filename; } // Old folders go only after the new one is in place; the automatic path keeps them for cached pages. $previous = is_array( $config['previous_folders'] ?? null ) ? $config['previous_folders'] : []; if ( $old_folder && $old_folder !== $new_folder_name ) { if ( $keep_previous ) { $previous[ $old_folder ] = time(); } else { self::delete_folder( $base_dir, $old_folder ); } } foreach ( $previous as $folder => $retired_at ) { if ( ! $keep_previous || (int) $retired_at < time() - self::PREVIOUS_FOLDER_GRACE ) { self::delete_folder( $base_dir, (string) $folder ); unset( $previous[ $folder ] ); } } // Save the new configuration $new_config = [ 'folder_name' => $new_folder_name, 'lookup_table' => $lookup_table, 'last_generated' => time(), ]; if ( $previous ) { $new_config['previous_folders'] = $previous; } update_option( Constants::OPTION_PREFIX . self::CONFIG_OPTION_NAME, $new_config, true ); return true; } /** * The files to mask: each registered asset plus its minified or source twin, so the lookup table covers * normal pages and debug sessions (SCRIPT_DEBUG, debugger level 2) whichever mode the rebuild ran in. * * @param array $assets Disguisable assets (handle => ['path' => ...]). * * @return string[] Absolute file paths. */ public static function asset_variants( array $assets ): array { $paths = []; foreach ( $assets as $asset_data ) { $path = isset( $asset_data['path'] ) ? wp_normalize_path( (string) $asset_data['path'] ) : ''; if ( '' === $path ) { continue; } $paths[ $path ] = $path; if ( ! str_ends_with( $path, '.js' ) ) { continue; } $dir = dirname( $path ); $file = basename( $path ); $twin = 'build' === basename( $dir ) ? dirname( $dir ) . '/' . $file : $dir . '/build/' . $file; if ( is_file( $twin ) ) { $paths[ $twin ] = $twin; } } return array_values( $paths ); } /** * Deletes one of our asset folders below the uploads dir. * * @param string $base_dir Uploads base dir with trailing slash. * @param string $folder Folder name. * * @return void */ private static function delete_folder( string $base_dir, string $folder ): void { global $wp_filesystem; // Only ever our own generated folder names, never a path. if ( ! preg_match( '/^adpr_assets_[A-Za-z0-9]+$/', $folder ) ) { return; } if ( $wp_filesystem->is_dir( $base_dir . $folder ) ) { $wp_filesystem->rmdir( $base_dir . $folder, true ); } } }