result). * * @var array */ protected static $cache = []; /** * Load patterns from the database file. * * @return array */ public static function load_patterns() { if ( self::$patterns !== null ) { return self::$patterns; } // Use dynamic path calculation since AS_CM_DIR may not be defined in REST context $plugin_dir = defined( 'AS_CM_DIR' ) ? AS_CM_DIR : dirname( dirname( dirname( __DIR__ ) ) ) . '/'; $file = $plugin_dir . 'includes/data/inline-patterns.php'; if ( ! file_exists( $file ) ) { self::$patterns = []; return self::$patterns; } $patterns = include $file; if ( ! is_array( $patterns ) ) { self::$patterns = []; return self::$patterns; } self::$patterns = $patterns; return self::$patterns; } /** * Detect service from inline script content. * * @param string $content The script content to analyze. * @return array|null Detection result or null if not detected. */ public static function detect( $content ) { if ( empty( $content ) || ! is_string( $content ) ) { return null; } // Generate hash for caching. $hash = self::hash_content( $content ); // Check cache first. if ( isset( self::$cache[ $hash ] ) ) { return self::$cache[ $hash ]; } $patterns = self::load_patterns(); foreach ( $patterns as $pattern_data ) { if ( empty( $pattern_data['pattern'] ) ) { continue; } $regex = $pattern_data['pattern']; // Ensure pattern has delimiters. if ( @preg_match( $regex, '' ) === false ) { continue; } if ( preg_match( $regex, $content ) ) { $result = [ 'detected' => true, 'service' => $pattern_data['service'] ?? 'Unknown', 'category' => $pattern_data['category'] ?? 'unclassified', 'blocking' => $pattern_data['blocking'] ?? null, 'cookies' => $pattern_data['cookies'] ?? [], 'hosts' => $pattern_data['hosts'] ?? [], 'detection_method' => 'pattern', 'pattern_matched' => $regex, 'hash' => $hash, 'confidence' => 1.0, ]; self::$cache[ $hash ] = $result; return $result; } } // Not detected. $result = [ 'detected' => false, 'service' => null, 'category' => null, 'blocking' => null, 'detection_method' => null, 'hash' => $hash, 'confidence' => 0, ]; self::$cache[ $hash ] = $result; return $result; } /** * Detect multiple scripts at once. * * @param array $scripts Array of script contents or script objects with 'content' key. * @return array Array of detection results. */ public static function detect_batch( $scripts ) { $results = []; foreach ( $scripts as $index => $script ) { $content = is_array( $script ) ? ( $script['content'] ?? $script['text'] ?? '' ) : $script; $result = self::detect( $content ); if ( $result ) { $result['index'] = $index; if ( is_array( $script ) ) { $result['original'] = $script; } $results[] = $result; } } return $results; } /** * Get all available patterns. * * @return array */ public static function get_patterns() { return self::load_patterns(); } /** * Get patterns for a specific category. * * @param string $category The category to filter by. * @return array */ public static function get_patterns_by_category( $category ) { $patterns = self::load_patterns(); return array_filter( $patterns, function ( $p ) use ( $category ) { return isset( $p['category'] ) && $p['category'] === $category; } ); } /** * Get all unique services from patterns. * * @return array */ public static function get_all_services() { $patterns = self::load_patterns(); $services = []; foreach ( $patterns as $pattern ) { if ( ! empty( $pattern['service'] ) ) { $key = sanitize_title( $pattern['service'] ); if ( ! isset( $services[ $key ] ) ) { $services[ $key ] = [ 'name' => $pattern['service'], 'category' => $pattern['category'] ?? 'unclassified', 'blocking' => $pattern['blocking'] ?? null, 'cookies' => $pattern['cookies'] ?? [], 'hosts' => $pattern['hosts'] ?? [], ]; } } } return $services; } /** * Generate a hash for script content. * * @param string $content The script content. * @return string SHA-256 hash (first 16 chars). */ public static function hash_content( $content ) { // Normalize content: remove whitespace variations. $normalized = preg_replace( '/\s+/', ' ', trim( $content ) ); return substr( hash( 'sha256', $normalized ), 0, 16 ); } /** * Get blocking configuration for a detected service. * * @param string $service_name The service name. * @return array|null Blocking configuration or null. */ public static function get_blocking_config( $service_name ) { $patterns = self::load_patterns(); foreach ( $patterns as $pattern ) { if ( isset( $pattern['service'] ) && $pattern['service'] === $service_name ) { return $pattern['blocking'] ?? null; } } return null; } /** * Get all function names that need to be intercepted. * * @param string|null $category Optional category filter. * @return array Array of function names grouped by category. */ public static function get_intercept_functions( $category = null ) { $patterns = self::load_patterns(); $functions = []; foreach ( $patterns as $pattern ) { if ( $category !== null && ( $pattern['category'] ?? '' ) !== $category ) { continue; } $cat = $pattern['category'] ?? 'unclassified'; if ( ! isset( $functions[ $cat ] ) ) { $functions[ $cat ] = []; } $blocking = $pattern['blocking'] ?? null; if ( $blocking && isset( $blocking['intercept'] ) && is_array( $blocking['intercept'] ) ) { foreach ( $blocking['intercept'] as $fn ) { if ( ! in_array( $fn, $functions[ $cat ], true ) ) { $functions[ $cat ][] = $fn; } } } } return $functions; } /** * Build JavaScript code for function interception. * * @param array $consent_map Current consent state per category. * @return string JavaScript code. */ public static function build_intercept_js( $consent_map = [] ) { $all_intercepts = self::get_intercept_functions(); $js_parts = []; $js_parts[] = '(function() {'; $js_parts[] = ' var ascmConsentMap = ' . wp_json_encode( $consent_map ) . ';'; $js_parts[] = ' var ascmBufferedCalls = {};'; $js_parts[] = ''; $js_parts[] = ' function isAllowed(category) {'; $js_parts[] = ' if (category === "required") return true;'; $js_parts[] = ' return !!ascmConsentMap[category];'; $js_parts[] = ' }'; $js_parts[] = ''; $js_parts[] = ' function bufferCall(fnName, category, args) {'; $js_parts[] = ' if (!ascmBufferedCalls[fnName]) ascmBufferedCalls[fnName] = [];'; $js_parts[] = ' ascmBufferedCalls[fnName].push({ category: category, args: Array.prototype.slice.call(args) });'; $js_parts[] = ' }'; $js_parts[] = ''; $js_parts[] = ' function flushBuffered(fnName, originalFn) {'; $js_parts[] = ' if (!ascmBufferedCalls[fnName]) return;'; $js_parts[] = ' var calls = ascmBufferedCalls[fnName];'; $js_parts[] = ' ascmBufferedCalls[fnName] = [];'; $js_parts[] = ' for (var i = 0; i < calls.length; i++) {'; $js_parts[] = ' if (isAllowed(calls[i].category)) {'; $js_parts[] = ' originalFn.apply(null, calls[i].args);'; $js_parts[] = ' }'; $js_parts[] = ' }'; $js_parts[] = ' }'; $js_parts[] = ''; foreach ( $all_intercepts as $category => $functions ) { foreach ( $functions as $fn_name ) { // Handle nested properties like 'dataLayer.push'. if ( strpos( $fn_name, '.' ) !== false ) { $parts = explode( '.', $fn_name ); $obj = $parts[0]; $method = $parts[1]; $safe_id = str_replace( '.', '_', $fn_name ); $js_parts[] = ' // Intercept ' . $fn_name . ' (' . $category . ')'; $js_parts[] = ' (function() {'; $js_parts[] = ' var checkInterval = setInterval(function() {'; $js_parts[] = ' if (typeof window["' . $obj . '"] !== "undefined" && typeof window["' . $obj . '"]["' . $method . '"] === "function") {'; $js_parts[] = ' clearInterval(checkInterval);'; $js_parts[] = ' var original_' . $safe_id . ' = window["' . $obj . '"]["' . $method . '"];'; $js_parts[] = ' window["' . $obj . '"]["' . $method . '"] = function() {'; $js_parts[] = ' if (!isAllowed("' . $category . '")) {'; $js_parts[] = ' bufferCall("' . $fn_name . '", "' . $category . '", arguments);'; $js_parts[] = ' return;'; $js_parts[] = ' }'; $js_parts[] = ' return original_' . $safe_id . '.apply(this, arguments);'; $js_parts[] = ' };'; $js_parts[] = ' }'; $js_parts[] = ' }, 50);'; $js_parts[] = ' setTimeout(function() { clearInterval(checkInterval); }, 10000);'; $js_parts[] = ' })();'; $js_parts[] = ''; } else { $js_parts[] = ' // Intercept ' . $fn_name . ' (' . $category . ')'; $js_parts[] = ' (function() {'; $js_parts[] = ' var original_' . $fn_name . ' = window["' . $fn_name . '"];'; $js_parts[] = ' var queue_' . $fn_name . ' = [];'; $js_parts[] = ' window["' . $fn_name . '"] = function() {'; $js_parts[] = ' if (!isAllowed("' . $category . '")) {'; $js_parts[] = ' bufferCall("' . $fn_name . '", "' . $category . '", arguments);'; $js_parts[] = ' return;'; $js_parts[] = ' }'; $js_parts[] = ' if (typeof original_' . $fn_name . ' === "function") {'; $js_parts[] = ' return original_' . $fn_name . '.apply(this, arguments);'; $js_parts[] = ' }'; $js_parts[] = ' };'; $js_parts[] = ' // Watch for late definition'; $js_parts[] = ' var checkInterval = setInterval(function() {'; $js_parts[] = ' if (typeof window["' . $fn_name . '"] === "function" && window["' . $fn_name . '"] !== original_' . $fn_name . ') {'; $js_parts[] = ' return; // Already wrapped'; $js_parts[] = ' }'; $js_parts[] = ' }, 100);'; $js_parts[] = ' setTimeout(function() { clearInterval(checkInterval); }, 5000);'; $js_parts[] = ' })();'; $js_parts[] = ''; } } } $js_parts[] = ' // Listen for consent changes'; $js_parts[] = ' window.addEventListener("ascm:consent-change", function(e) {'; $js_parts[] = ' if (e.detail && e.detail.consent) {'; $js_parts[] = ' ascmConsentMap = e.detail.consent;'; $js_parts[] = ' }'; $js_parts[] = ' });'; $js_parts[] = ''; $js_parts[] = ' window.ascmInlineBlocking = {'; $js_parts[] = ' getBuffered: function() { return ascmBufferedCalls; },'; $js_parts[] = ' updateConsent: function(map) { ascmConsentMap = map; }'; $js_parts[] = ' };'; $js_parts[] = '})();'; return implode( "\n", $js_parts ); } /** * Clear the detection cache. */ public static function clear_cache() { self::$cache = []; } /** * Get statistics about detected inline scripts from a scan. * * @param array $inline_scripts Array of inline script data. * @return array Statistics. */ public static function get_statistics( $inline_scripts ) { $stats = [ 'total' => count( $inline_scripts ), 'detected' => 0, 'undetected' => 0, 'by_category' => [], 'by_service' => [], ]; foreach ( $inline_scripts as $script ) { $result = self::detect( $script['content'] ?? $script['text'] ?? '' ); if ( $result && $result['detected'] ) { $stats['detected']++; $cat = $result['category'] ?? 'unclassified'; if ( ! isset( $stats['by_category'][ $cat ] ) ) { $stats['by_category'][ $cat ] = 0; } $stats['by_category'][ $cat ]++; $svc = $result['service'] ?? 'Unknown'; if ( ! isset( $stats['by_service'][ $svc ] ) ) { $stats['by_service'][ $svc ] = 0; } $stats['by_service'][ $svc ]++; } else { $stats['undetected']++; } } return $stats; } }