Completed
Push — add/sync-partial-sync-checksum... ( 93f4e2...c9ed3f )
by
unknown
253:26 queued 243:12
created

Jetpack_Google_Analytics_Legacy::insert_code()   B

Complexity

Conditions 8
Paths 9

Size

Total Lines 70

Duplication

Lines 11
Ratio 15.71 %

Importance

Changes 0
Metric Value
cc 8
nc 9
nop 0
dl 11
loc 70
rs 7.4101
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
		$custom_vars = array(
81
			"_gaq.push(['_setAccount', '{$tracking_id}']);",
82
		);
83
84
		$track = array();
85 View Code Duplication
		if ( is_404() ) {
86
			// This is a 404 and we are supposed to track them.
87
			$custom_vars[] = "_gaq.push(['_trackEvent', '404', document.location.href, document.referrer]);";
88
		} elseif (
89
			is_search()
90
			&& isset( $_REQUEST['s'] )
91
		) {
92
			// Set track for searches, if it's a search, and we are supposed to.
93
			$track['data'] = sanitize_text_field( wp_unslash( $_REQUEST['s'] ) ); // Input var okay.
94
			$track['code'] = 'search';
95
		}
96
97
		if ( ! empty( $track ) ) {
98
			$track['url'] = $this->_get_url( $track );
99
			// adjust the code that we output, account for both types of tracking.
100
			$track['url'] = esc_js( str_replace( '&', '&amp;', $track['url'] ) );
101
			$custom_vars[] = "_gaq.push(['_trackPageview','{$track['url']}']);";
102
		} else {
103
			$custom_vars[] = "_gaq.push(['_trackPageview']);";
104
		}
105
106
		/**
107
		 * Allow for additional elements to be added to the classic Google Analytics queue (_gaq) array
108
		 *
109
		 * @since 5.4.0
110
		 *
111
		 * @param array $custom_vars Array of classic Google Analytics queue elements
112
		 */
113
		$custom_vars = apply_filters( 'jetpack_wga_classic_custom_vars', $custom_vars );
114
115
		// Ref: https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce#Example
116
		printf(
117
			"<!-- Jetpack Google Analytics -->
118
			<script type='text/javascript'>
119
				var _gaq = _gaq || [];
120
				%s
121
				(function() {
122
					var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
123
					ga.src = ('https:' === document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
124
					var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
125
				})();
126
			</script>\r\n",
127
			implode( "\r\n", $custom_vars )
128
		);
129
	}
130
131
	/**
132
	 * Used to filter in the anonymize IP snippet to the custom vars array for classic analytics
133
	 * Ref https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApi_gat#_gat._anonymizelp
134
	 * @param array custom vars to be filtered
135
	 * @return array possibly updated custom vars
136
	 */
137
	public function jetpack_wga_classic_anonymize_ip( $custom_vars ) {
138
		if ( Jetpack_Google_Analytics_Options::anonymize_ip_is_enabled() ) {
139
			array_push( $custom_vars, "_gaq.push(['_gat._anonymizeIp']);" );
140
		}
141
142
		return $custom_vars;
143
	}
144
145
	/**
146
	 * Used to filter in the order details to the custom vars array for classic analytics
147
	 * @param array custom vars to be filtered
148
	 * @return array possibly updated custom vars
149
	 */
150
	public function jetpack_wga_classic_track_purchases( $custom_vars ) {
151
		global $wp;
152
153
		if ( ! class_exists( 'WooCommerce' ) ) {
154
			return $custom_vars;
155
		}
156
157
		if ( ! Jetpack_Google_Analytics_Options::has_tracking_code() ) {
158
			return;
159
		}
160
161
		// Ref: https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce#Example
162
		if ( ! Jetpack_Google_Analytics_Options::track_purchases_is_enabled() ) {
163
			return $custom_vars;
164
		}
165
166
		$minimum_woocommerce_active = class_exists( 'WooCommerce' ) && version_compare( WC_VERSION, '3.0', '>=' );
167
		if ( $minimum_woocommerce_active && is_order_received_page() ) {
168
			$order_id = isset( $wp->query_vars['order-received'] ) ? $wp->query_vars['order-received'] : 0;
169
			if ( 0 < $order_id && 1 != get_post_meta( $order_id, '_ga_tracked', true ) ) {
170
				$order = new WC_Order( $order_id );
171
172
				// [ '_add_Trans', '123', 'Site Title', '21.00', '1.00', '5.00', 'Snohomish', 'WA', 'USA' ]
173
				array_push(
174
					$custom_vars,
175
					sprintf(
176
						'_gaq.push( %s );', json_encode(
177
							array(
178
								'_addTrans',
179
								(string) $order->get_order_number(),
180
								get_bloginfo( 'name' ),
181
								(string) $order->get_total(),
182
								(string) $order->get_total_tax(),
183
								(string) $order->get_total_shipping(),
184
								(string) $order->get_billing_city(),
185
								(string) $order->get_billing_state(),
186
								(string) $order->get_billing_country()
187
							)
188
						)
189
					)
190
				);
191
192
				// Order items
193
				if ( $order->get_items() ) {
194
					foreach ( $order->get_items() as $item ) {
195
						$product = $order->get_product_from_item( $item );
196
						$product_sku_or_id = $product->get_sku() ? $product->get_sku() : $product->get_id();
197
198
						array_push(
199
							$custom_vars,
200
							sprintf(
201
								'_gaq.push( %s );', json_encode(
202
									array(
203
										'_addItem',
204
										(string) $order->get_order_number(),
205
										(string) $product_sku_or_id,
206
										$item['name'],
207
										Jetpack_Google_Analytics_Utils::get_product_categories_concatenated( $product ),
208
										(string) $order->get_item_total( $item ),
209
										(string) $item['qty']
210
									)
211
								)
212
							)
213
						);
214
					}
215
				} // get_items
216
217
				// Mark the order as tracked
218
				update_post_meta( $order_id, '_ga_tracked', 1 );
219
				array_push( $custom_vars, "_gaq.push(['_trackTrans']);" );
220
			} // order not yet tracked
221
		} // is order received page
222
223
		return $custom_vars;
224
	}
225
226
	/**
227
	 * Used to add footer javascript to track user clicking on add-to-cart buttons
228
	 * on single views (.single_add_to_cart_button) and list views (.add_to_cart_button)
229
	 */
230
	public function jetpack_wga_classic_track_add_to_cart() {
231
		if ( ! class_exists( 'WooCommerce' ) ) {
232
			return;
233
		}
234
235
		if ( ! Jetpack_Google_Analytics_Options::has_tracking_code() ) {
236
			return;
237
		}
238
239
		if ( ! Jetpack_Google_Analytics_Options::track_add_to_cart_is_enabled() ) {
240
			return;
241
		}
242
243
		if ( is_product() ) { // product page
244
			global $product;
245
			$product_sku_or_id = $product->get_sku() ? $product->get_sku() : "#" + $product->get_id();
246
			wc_enqueue_js(
247
				"$( '.single_add_to_cart_button' ).click( function() {
248
					_gaq.push(['_trackEvent', 'Products', 'Add to Cart', '#" . esc_js( $product_sku_or_id ) . "']);
249
				} );"
250
			);
251
		} else if ( is_woocommerce() ) { // any other page that uses templates (like product lists, archives, etc)
252
			wc_enqueue_js(
253
				"$( '.add_to_cart_button:not(.product_type_variable, .product_type_grouped)' ).click( function() {
254
					var label = $( this ).data( 'product_sku' ) ? $( this ).data( 'product_sku' ) : '#' + $( this ).data( 'product_id' );
255
					_gaq.push(['_trackEvent', 'Products', 'Add to Cart', label]);
256
				} );"
257
			);
258
		}
259
	}
260
}
261