Completed
Push — renovate/debug-4.x ( e10916...91e0c8 )
by
unknown
86:28 queued 77:02
created

Jetpack_Google_Analytics_Legacy::render_ga_code()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 52

Duplication

Lines 11
Ratio 21.15 %

Importance

Changes 0
Metric Value
cc 5
nc 6
nop 1
dl 11
loc 52
rs 8.7361
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Jetpack_Google_Analytics_Legacy hooks and enqueues support for ga.js
5
 * https://developers.google.com/analytics/devguides/collection/gajs/
6
 *
7
 * @author Aaron D. Campbell (original)
8
 * @author allendav
9
 */
10
11
/**
12
 * Bail if accessed directly
13
 */
14
if ( ! defined( 'ABSPATH' ) ) {
15
	exit;
16
}
17
18
class Jetpack_Google_Analytics_Legacy {
19
	public function __construct() {
20
		add_filter( 'jetpack_wga_classic_custom_vars', array( $this, 'jetpack_wga_classic_anonymize_ip' ) );
21
		add_filter( 'jetpack_wga_classic_custom_vars', array( $this, 'jetpack_wga_classic_track_purchases' ) );
22
		add_action( 'wp_head', array( $this, 'insert_code' ), 999 );
23
		add_action( 'wp_footer', array( $this, 'jetpack_wga_classic_track_add_to_cart' ) );
24
	}
25
26
	/**
27
	 * Used to generate a tracking URL
28
	 * Called exclusively by insert_code
29
	 *
30
	 * @param array $track - Must have ['data'] and ['code'].
31
	 * @return string - Tracking URL
32
	 */
33
	private function _get_url( $track ) {
34
		$site_url = ( is_ssl() ? 'https://' : 'http://' ) . sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ); // Input var okay.
35
		foreach ( $track as $k => $value ) {
36
			if ( strpos( strtolower( $value ), strtolower( $site_url ) ) === 0 ) {
37
				$track[ $k ] = substr( $track[ $k ], strlen( $site_url ) );
38
			}
39
			if ( 'data' === $k ) {
40
				$track[ $k ] = preg_replace( '/^https?:\/\/|^\/+/i', '', $track[ $k ] );
41
			}
42
43
			// This way we don't lose search data.
44
			if ( 'data' === $k && 'search' === $track['code'] ) {
45
				$track[ $k ] = rawurlencode( $track[ $k ] );
46
			} else {
47
				$track[ $k ] = preg_replace( '/[^a-z0-9\.\/\+\?=-]+/i', '_', $track[ $k ] );
48
			}
49
50
			$track[ $k ] = trim( $track[ $k ], '_' );
51
		}
52
		$char = ( strpos( $track['data'], '?' ) === false ) ? '?' : '&amp;';
53
		return str_replace( "'", "\'", "/{$track['code']}/{$track['data']}{$char}referer=" . rawurlencode( isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : '' ) ); // Input var okay.
54
	}
55
56
	/**
57
	 * This injects the Google Analytics code into the footer of the page.
58
	 * Called exclusively by wp_head action
59
	 */
60
	public function insert_code() {
61
		$tracking_id = Jetpack_Google_Analytics_Options::get_tracking_code();
62
		if ( empty( $tracking_id ) ) {
63
			echo "<!-- Your Google Analytics Plugin is missing the tracking ID -->\r\n";
64
			return;
65
		}
66
67
		// If we're in the admin_area, return without inserting code.
68
		if ( is_admin() ) {
69
			return;
70
		}
71
72
		if ( Jetpack_AMP_Support::is_amp_request() ) {
73
			// For Reader mode — legacy.
74
			add_filter( 'amp_post_template_analytics', 'Jetpack_Google_Analytics::amp_analytics_entries', 1000 );
75
			// For Standard and Transitional modes.
76
			add_filter( 'amp_analytics_entries', 'Jetpack_Google_Analytics::amp_analytics_entries', 1000 );
77
			return;
78
		}
79
80
		if ( 'G-' === substr( $tracking_id, 0, 2 ) ) {
81
			$this->render_gtag_code( $tracking_id );
82
		} else {
83
			$this->render_ga_code( $tracking_id );
84
		}
85
	}
86
87
	/**
88
	 * Renders legacy ga.js code.
89
	 *
90
	 * @param string $tracking_id Google Analytics measurement ID.
91
	 */
92
	private function render_ga_code( $tracking_id ) {
93
		$custom_vars = array(
94
			"_gaq.push(['_setAccount', '{$tracking_id}']);",
95
		);
96
97
		$track = array();
98 View Code Duplication
		if ( is_404() ) {
99
			// This is a 404 and we are supposed to track them.
100
			$custom_vars[] = "_gaq.push(['_trackEvent', '404', document.location.href, document.referrer]);";
101
		} elseif (
102
			is_search()
103
			&& isset( $_REQUEST['s'] )
104
		) {
105
			// Set track for searches, if it's a search, and we are supposed to.
106
			$track['data'] = sanitize_text_field( wp_unslash( $_REQUEST['s'] ) ); // Input var okay.
107
			$track['code'] = 'search';
108
		}
109
110
		if ( ! empty( $track ) ) {
111
			$track['url'] = $this->_get_url( $track );
112
			// adjust the code that we output, account for both types of tracking.
113
			$track['url']  = esc_js( str_replace( '&', '&amp;', $track['url'] ) );
114
			$custom_vars[] = "_gaq.push(['_trackPageview','{$track['url']}']);";
115
		} else {
116
			$custom_vars[] = "_gaq.push(['_trackPageview']);";
117
		}
118
119
		/**
120
		 * Allow for additional elements to be added to the classic Google Analytics queue (_gaq) array
121
		 *
122
		 * @since 5.4.0
123
		 *
124
		 * @param array $custom_vars Array of classic Google Analytics queue elements
125
		 */
126
		$custom_vars = apply_filters( 'jetpack_wga_classic_custom_vars', $custom_vars );
127
128
		// Ref: https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce#Example
129
		printf(
130
			"<!-- Jetpack Google Analytics -->
131
			<script type='text/javascript'>
132
				var _gaq = _gaq || [];
133
				%s
134
				(function() {
135
					var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
136
					ga.src = ('https:' === document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
137
					var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
138
				})();
139
			</script>
140
			<!-- End Jetpack Google Analytics -->\r\n",
141
			implode( "\r\n", $custom_vars )
142
		);
143
	}
144
145
	/**
146
	 * Renders new gtag code.
147
	 *
148
	 * @param string $tracking_id Google Analytics measurement ID.
149
	 */
150
	private function render_gtag_code( $tracking_id ) {
151
		/**
152
		 * Allow for additional elements to be added to the Global Site Tags array.
153
		 *
154
		 * @since 9.2.0
155
		 *
156
		 * @param array $universal_commands Array of gtag function calls.
157
		 */
158
		$universal_commands = apply_filters( 'jetpack_gtag_universal_commands', array() );
159
		$custom_vars        = array();
160
		if ( is_404() ) {
161
			$custom_vars[] = array(
162
				'event',
163
				'exception',
164
				array(
165
					'description' => '404',
166
					'fatal'       => false,
167
				),
168
			);
169
		}
170
		// phpcs:disable WordPress.WP.EnqueuedResources.NonEnqueuedScript
171
		?>
172
		<!-- Jetpack Google Analytics -->
173
		<script async src='https://www.googletagmanager.com/gtag/js?id=<?php echo esc_attr( $tracking_id ); ?>'></script>
174
		<script>
175
			window.dataLayer = window.dataLayer || [];
176
			function gtag() { dataLayer.push( arguments ); }
177
			gtag( 'js', new Date() );
178
			gtag( 'config', <?php echo wp_json_encode( $tracking_id ); ?> );
179
			<?php
180
			foreach ( $universal_commands as $command ) {
181
				echo 'gtag( ' . implode( ', ', array_map( 'wp_json_encode', $command ) ) . " );\n";
182
			}
183
			foreach ( $custom_vars as $var ) {
184
				echo 'gtag( ' . implode( ', ', array_map( 'wp_json_encode', $var ) ) . " );\n";
185
			}
186
			?>
187
		</script>
188
		<!-- End Jetpack Google Analytics -->
189
		<?php
190
		// phpcs:enable
191
	}
192
193
	/**
194
	 * Used to filter in the anonymize IP snippet to the custom vars array for classic analytics
195
	 * Ref https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApi_gat#_gat._anonymizelp
196
	 *
197
	 * @param array custom vars to be filtered
198
	 * @return array possibly updated custom vars
199
	 */
200
	public function jetpack_wga_classic_anonymize_ip( $custom_vars ) {
201
		if ( Jetpack_Google_Analytics_Options::anonymize_ip_is_enabled() ) {
202
			array_push( $custom_vars, "_gaq.push(['_gat._anonymizeIp']);" );
203
		}
204
205
		return $custom_vars;
206
	}
207
208
	/**
209
	 * Used to filter in the order details to the custom vars array for classic analytics
210
	 *
211
	 * @param array custom vars to be filtered
212
	 * @return array possibly updated custom vars
213
	 */
214
	public function jetpack_wga_classic_track_purchases( $custom_vars ) {
215
		global $wp;
216
217
		if ( ! class_exists( 'WooCommerce' ) ) {
218
			return $custom_vars;
219
		}
220
221
		if ( ! Jetpack_Google_Analytics_Options::has_tracking_code() ) {
222
			return;
223
		}
224
225
		// Ref: https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce#Example
226
		if ( ! Jetpack_Google_Analytics_Options::track_purchases_is_enabled() ) {
227
			return $custom_vars;
228
		}
229
230
		$minimum_woocommerce_active = class_exists( 'WooCommerce' ) && version_compare( WC_VERSION, '3.0', '>=' );
231
		if ( $minimum_woocommerce_active && is_order_received_page() ) {
232
			$order_id = isset( $wp->query_vars['order-received'] ) ? $wp->query_vars['order-received'] : 0;
233
			if ( 0 < $order_id && 1 != get_post_meta( $order_id, '_ga_tracked', true ) ) {
234
				$order = new WC_Order( $order_id );
235
236
				// [ '_add_Trans', '123', 'Site Title', '21.00', '1.00', '5.00', 'Snohomish', 'WA', 'USA' ]
237
				array_push(
238
					$custom_vars,
239
					sprintf(
240
						'_gaq.push( %s );',
241
						json_encode(
242
							array(
243
								'_addTrans',
244
								(string) $order->get_order_number(),
245
								get_bloginfo( 'name' ),
246
								(string) $order->get_total(),
247
								(string) $order->get_total_tax(),
248
								(string) $order->get_total_shipping(),
249
								(string) $order->get_billing_city(),
250
								(string) $order->get_billing_state(),
251
								(string) $order->get_billing_country(),
252
							)
253
						)
254
					)
255
				);
256
257
				// Order items
258
				if ( $order->get_items() ) {
259
					foreach ( $order->get_items() as $item ) {
260
						$product           = $order->get_product_from_item( $item );
261
						$product_sku_or_id = $product->get_sku() ? $product->get_sku() : $product->get_id();
262
263
						array_push(
264
							$custom_vars,
265
							sprintf(
266
								'_gaq.push( %s );',
267
								json_encode(
268
									array(
269
										'_addItem',
270
										(string) $order->get_order_number(),
271
										(string) $product_sku_or_id,
272
										$item['name'],
273
										Jetpack_Google_Analytics_Utils::get_product_categories_concatenated( $product ),
274
										(string) $order->get_item_total( $item ),
275
										(string) $item['qty'],
276
									)
277
								)
278
							)
279
						);
280
					}
281
				} // get_items
282
283
				// Mark the order as tracked
284
				update_post_meta( $order_id, '_ga_tracked', 1 );
285
				array_push( $custom_vars, "_gaq.push(['_trackTrans']);" );
286
			} // order not yet tracked
287
		} // is order received page
288
289
		return $custom_vars;
290
	}
291
292
	/**
293
	 * Used to add footer javascript to track user clicking on add-to-cart buttons
294
	 * on single views (.single_add_to_cart_button) and list views (.add_to_cart_button)
295
	 */
296
	public function jetpack_wga_classic_track_add_to_cart() {
297
		if ( ! class_exists( 'WooCommerce' ) ) {
298
			return;
299
		}
300
301
		if ( ! Jetpack_Google_Analytics_Options::has_tracking_code() ) {
302
			return;
303
		}
304
305
		if ( ! Jetpack_Google_Analytics_Options::track_add_to_cart_is_enabled() ) {
306
			return;
307
		}
308
309
		if ( is_product() ) { // product page
310
			global $product;
311
			$product_sku_or_id = $product->get_sku() ? $product->get_sku() : '#' + $product->get_id();
312
			wc_enqueue_js(
313
				"$( '.single_add_to_cart_button' ).click( function() {
314
					_gaq.push(['_trackEvent', 'Products', 'Add to Cart', '#" . esc_js( $product_sku_or_id ) . "']);
315
				} );"
316
			);
317
		} elseif ( is_woocommerce() ) { // any other page that uses templates (like product lists, archives, etc)
318
			wc_enqueue_js(
319
				"$( '.add_to_cart_button:not(.product_type_variable, .product_type_grouped)' ).click( function() {
320
					var label = $( this ).data( 'product_sku' ) ? $( this ).data( 'product_sku' ) : '#' + $( this ).data( 'product_id' );
321
					_gaq.push(['_trackEvent', 'Products', 'Add to Cart', label]);
322
				} );"
323
			);
324
		}
325
	}
326
}
327