init(); } return self::$instance; } /** * Initializes the service. * Reads the configuration and registers hooks if the module is active and configured. */ public function init(): void { $this->config = Settings::get_direct_option( AssetMaskingAdmin::CONFIG_OPTION_NAME, [] ); if ( empty( $this->config['folder_name'] ) || empty( $this->config['lookup_table'] ) ) { return; } $upload_dir = wp_upload_dir(); if ( empty( $upload_dir['baseurl'] ) ) { return; } $this->uploads_base_url = trailingslashit( $upload_dir['baseurl'] ); $this->plugin_url_path = wp_normalize_path( ltrim( wp_parse_url( plugin_dir_url( defined( 'ADPRESSO_FILE' ) ? ADPRESSO_FILE : __FILE__ ), PHP_URL_PATH ), '/' ) ); $this->hooks(); } /** * Registers the necessary filters to rewrite asset URLs. */ private function hooks(): void { // Use a high priority to run after scripts are registered but before they are printed. add_filter( 'script_loader_src', [ $this, 'rewrite_asset_url' ], 999, 1 ); add_filter( 'style_loader_src', [ $this, 'rewrite_asset_url' ], 999, 1 ); } /** * The callback function that rewrites the asset URL if it's in our lookup table. * * @param string $src The original URL of the asset. * * @return string The original or the new, disguised URL. */ public function rewrite_asset_url( string $src ): string { if ( empty( $src ) ) { return $src; } $path = wp_parse_url( $src, PHP_URL_PATH ); if ( ! $path ) { return $src; } $normalized = wp_normalize_path( ltrim( $path, '/' ) ); $folder_name = $this->config['folder_name'] ?? ''; $masked_base = wp_normalize_path( ltrim( wp_parse_url( $this->uploads_base_url, PHP_URL_PATH ) . $folder_name . '/', '/' ) ); if ( str_starts_with( $normalized, $masked_base ) ) { return $src; } $in_main = str_starts_with( $normalized, $this->plugin_url_path ); if ( ! $in_main ) { return $src; } // 3) Lookup: root-relative vs. table if ( isset( $this->config['lookup_table'][ $normalized ] ) ) { $new_src = trailingslashit( $this->uploads_base_url . $this->config['folder_name'] ) . $this->config['lookup_table'][ $normalized ]; // Keep the original query string. $qs = wp_parse_url( $src, PHP_URL_QUERY ); if ( $qs ) { $new_src .= '?' . $qs; } return esc_url( $new_src ); } // If not found in the table, return the original URL. return $src; } }