HEX
Server: nginx
System: Linux pool195-106-36.bur.atomicsites.net 6.12.57+deb12-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.12.57-1~bpo12+1 (2025-11-17) x86_64
User: (0)
PHP: 8.3.32
Disabled: pcntl_fork
Upload Files
File: //wordpress/plugins/wp-cloud-client/1.2.1/src/Analytics/GoogleAnalytics4.php
<?php

declare(strict_types=1);

namespace VPlugins\WPCloudClient\Analytics;

use VPlugins\WPCloudClient\Settings\SettingsRepository;

/**
 * Injects Google Analytics 4 tracking script into the site's <head>.
 *
 * Supports two tracking IDs:
 *   1. A platform ID selected by WSP_SITE_ENVIRONMENT (DEMO or PROD).
 *   2. A user-supplied custom ID saved in the plugin settings.
 *
 * Both platform IDs are reserved and cannot be set by the user as a custom ID.
 */
class GoogleAnalytics4 {

	private const TRACKING_ID_PROD = 'G-3KT4C16M4V';
	private const TRACKING_ID_DEMO = 'G-WB452F0YCY';

	/**
	 * Constructor.
	 *
	 * @param SettingsRepository $settings Plugin settings repository.
	 */
	public function __construct(
		private readonly SettingsRepository $settings,
	) {}

	/**
	 * Register the analytics script hook.
	 *
	 * @return void
	 */
	public function register(): void {
		add_action( 'wp_head', [ $this, 'injectScript' ] );
	}

	/**
	 * Sanitizes and validates a user-submitted GA4 tracking ID.
	 *
	 * Called via register_setting sanitize_callback.
	 *
	 * @param string $input The raw tracking ID input.
	 * @return string The sanitized tracking ID.
	 */
	public function sanitizeTrackingId( string $input ): string {
		$input = strtoupper( trim( $input ) );

		if ( '' === $input ) {
			return '';
		}

		if ( in_array( $input, [ self::TRACKING_ID_PROD, self::TRACKING_ID_DEMO ], true ) ) {
			add_settings_error(
				'wpcc_settings',
				'wpcc_ga4_reserved',
				sprintf( '%s %s', $input, __( 'is already in use', 'wp-cloud-client' ) ),
				'error',
			);
			return $this->settings->getGa4TrackingId() ?? '';
		}

		if ( ! preg_match( '/^G-[A-Z0-9]{10}$/', $input ) ) {
			add_settings_error(
				'wpcc_settings',
				'wpcc_ga4_invalid',
				sprintf( '%s: %s', __( 'Invalid Google Analytics 4 Tracking ID', 'wp-cloud-client' ), $input ),
				'error',
			);
			return $this->settings->getGa4TrackingId() ?? '';
		}

		return $input;
	}

	/**
	 * Outputs the gtag script tags into wp_head.
	 */
	public function injectScript(): void {
		$trackingIds = $this->getTrackingIds();

		if ( empty( $trackingIds ) ) {
			return;
		}

		$vendastaSiteId = $this->settings->getVendastaSiteId();
		if ( null === $vendastaSiteId ) {
			error_log( '[WP Cloud Client] WSP_SITE_ID not found in Atomic_Persistent_Data — GA4 dimension1 will be empty.' );
		}
		$siteId  = (string) ( $vendastaSiteId ?? '' );
		$idsJson = wp_json_encode( $trackingIds );
		?>
		<script async src="https://www.googletagmanager.com/gtag/js?id=<?php echo esc_attr( $trackingIds[0] ); ?>"></script>
		<script>
			window.dataLayer = window.dataLayer || [];
			function gtag() { dataLayer.push(arguments); }
			var tracking_ids = <?php echo wp_json_encode( $trackingIds ); ?>;
			var site_id = '<?php echo esc_js( $siteId ); ?>';
			gtag('js', new Date());
			for (var i = 0; i < tracking_ids.length; i++) {
				gtag('config', tracking_ids[i], { 'dimension1': site_id });
				gtag('event', 'page_view',        { 'send_to': tracking_ids[i], 'dimension1': site_id });
				gtag('event', 'first_visit',      { 'send_to': tracking_ids[i], 'dimension1': site_id });
				gtag('event', 'engaged_sessions', { 'send_to': tracking_ids[i], 'dimension1': site_id });
				gtag('set', { 'siteSpeedSampleRate': 50 });
			}
		</script>
		<?php
	}

	/**
	 * Returns the active tracking ID list.
	 * Uses the user-supplied custom ID if set; otherwise falls back to the
	 * platform default — DEMO (G-WB452F0YCY) or PROD (G-3KT4C16M4V) — based on WSP_SITE_ENVIRONMENT.
	 */
	private function getTrackingIds(): array {
		$userTracking = $this->settings->getGa4TrackingId();
		if ( null !== $userTracking ) {
			return [ $userTracking ];
		}

		return [
			'DEMO' === $this->settings->getEnvironment()
				? self::TRACKING_ID_DEMO
				: self::TRACKING_ID_PROD,
		];
	}
}