get_all_settings(); if ( empty( $s['local_ga_enabled'] ) && empty( $s['local_gtm_id'] ) ) { return; } wp_dequeue_script( 'google-analytics' ); wp_deregister_script( 'google-analytics' ); } public function print_ga() { $s = \QWSpeedCache\Plugin::instance()->get_all_settings(); if ( ! empty( $s['cookie_consent_enabled'] ) && ! empty( $s['consent_block_analytics'] ) ) { $ok = isset( $_COOKIE['qwsc_consent'] ) && is_string( $_COOKIE['qwsc_consent'] ) && '1' === sanitize_text_field( wp_unslash( $_COOKIE['qwsc_consent'] ) ); if ( ! $ok ) { return; } } $s = \QWSpeedCache\Plugin::instance()->get_all_settings(); $gtm = isset( $s['local_gtm_id'] ) && is_string( $s['local_gtm_id'] ) ? trim( $s['local_gtm_id'] ) : ''; if ( ! preg_match( '/^GTM-[A-Z0-9]{4,20}$/', $gtm ) ) { $gtm = ''; } if ( $gtm && 0 === strpos( $gtm, 'GTM-' ) ) { $src = 'https://www.googletagmanager.com/gtm.js?id=' . rawurlencode( $gtm ); // Register a dependency-free handle so WordPress owns the inline snippet. // Keep GTM's original dynamic loader semantics (including dataLayer). wp_register_script( 'qwsc-local-gtm-bootstrap', false, array(), QWSC_VERSION, false ); wp_enqueue_script( 'qwsc-local-gtm-bootstrap' ); $inline = '(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({"gtm.start":new Date().getTime(),event:"gtm.js"});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!=="dataLayer"?"&l="+l:"";j.async=true;j.src=' . wp_json_encode( $src ) . '+dl;f.parentNode.insertBefore(j,f);})(window,document,"script","dataLayer",' . wp_json_encode( $gtm ) . ');'; wp_add_inline_script( 'qwsc-local-gtm-bootstrap', $inline, 'after' ); return; } if ( empty( $s['local_ga_enabled'] ) || empty( $s['local_ga_id'] ) ) { return; } $id = is_string( $s['local_ga_id'] ) ? trim( $s['local_ga_id'] ) : ''; if ( ! preg_match( '/^G-[A-Z0-9]{4,20}$/', $id ) ) { return; } // Load the vendor-hosted asset using WordPress's enqueue API. // Arbitrary custom script URLs and cached downloaded JS are not executed. $src = 'https://www.googletagmanager.com/gtag/js?id=' . rawurlencode( $id ); wp_enqueue_script( 'qwsc-local-ga', esc_url_raw( $src ), array(), QWSC_VERSION, false ); wp_script_add_data( 'qwsc-local-ga', 'async', true ); $inline = 'window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag("js",new Date());gtag("config",' . wp_json_encode( $id ) . ',{anonymize_ip:true});'; wp_add_inline_script( 'qwsc-local-ga', $inline, 'after' ); } /** * Retained compatibility entry point; executable remote mirrors are disabled. * * @return null */ public static function local_file_url() { return null; } /** @return null */ public static function local_gtm_url() { return null; } /** Legacy cron callback: no longer downloads executable JavaScript. */ public function mirror_script() {} /** Legacy cron callback: no longer downloads executable JavaScript. */ public function mirror_gtm() {} }