Completed
Push — add/8181-enhanced-google-analy... ( 492986...fd7aed )
by
unknown
36:24 queued 28:55
created

Jetpack_Google_Analytics_Legacy::insert_code()   B

Complexity

Conditions 6
Paths 8

Size

Total Lines 62
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 26
nc 8
nop 0
dl 0
loc 62
rs 8.6652
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 allendav 
8
*/
9
10
/**
11
* Bail if accessed directly
12
*/
13
if ( ! defined( 'ABSPATH' ) ) {
14
	exit;
15
}
16
17
class Jetpack_Google_Analytics_Legacy {
18
	public function __construct() {
19
		add_filter( 'jetpack_wga_classic_custom_vars', array( $this, 'jetpack_wga_classic_anonymize_ip' ) );
20
		add_filter( 'jetpack_wga_classic_custom_vars', array( $this, 'jetpack_wga_classic_track_purchases' ) );
21
		add_action( 'wp_footer', array( $this, 'insert_code' ) );
22
		add_action( 'wp_footer', array( $this, 'jetpack_wga_classic_track_add_to_cart' ) );
23
	}
24
25
	/**
26
	 * Used to generate a tracking URL
27
	 * Called exclusively by insert_code
28
	 *
29
	 * @param array $track - Must have ['data'] and ['code'].
30
	 * @return string - Tracking URL
31
	 */
32
	private function _get_url( $track ) {
33
		$site_url = ( is_ssl() ? 'https://':'http://' ) . sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ); // Input var okay.
34
		foreach ( $track as $k => $value ) {
35
			if ( strpos( strtolower( $value ), strtolower( $site_url ) ) === 0 ) {
36
				$track[ $k ] = substr( $track[ $k ], strlen( $site_url ) );
37
			}
38
			if ( 'data' === $k ) {
39
				$track[ $k ] = preg_replace( '/^https?:\/\/|^\/+/i', '', $track[ $k ] );
40
			}
41
42
			// This way we don't lose search data.
43
			if ( 'data' === $k && 'search' === $track['code'] ) {
44
				$track[ $k ] = rawurlencode( $track[ $k ] );
45
			} else {
46
				$track[ $k ] = preg_replace( '/[^a-z0-9\.\/\+\?=-]+/i', '_', $track[ $k ] );
47
			}
48
49
			$track[ $k ] = trim( $track[ $k ], '_' );
50
		}
51
		$char = ( strpos( $track['data'], '?' ) === false ) ? '?' : '&amp;';
52
		return str_replace( "'", "\'", "/{$track['code']}/{$track['data']}{$char}referer=" . rawurlencode( isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : '' ) ); // Input var okay.
53
	}
54
55
	/**
56
	 * This injects the Google Analytics code into the footer of the page.
57
	 * Called exclusively by wp_footer action
58
	 */
59
	public function insert_code() {
60
		$tracking_id = Jetpack_Google_Analytics_Options::get_tracking_code();
61
		if ( empty( $tracking_id ) ) {
62
			echo "<!-- Your Google Analytics Plugin is missing the tracking ID -->\r\n";
63
			return;
64
		}
65
66
		// If we're in the admin_area, return without inserting code.
67
		if ( is_admin() ) {
68
			return;
69
		}
70
71
		$custom_vars = array(
72
			"_gaq.push(['_setAccount', '{$tracking_id}']);",
73
		);
74
75
		$track = array();
76
		if ( is_404() ) {
77
			// This is a 404 and we are supposed to track them.
78
			$custom_vars[] = "_gaq.push(['_trackEvent', '404', document.location.href, document.referrer]);";
79
		} elseif ( is_search() ) {
80
			// Set track for searches, if it's a search, and we are supposed to.
81
			$track['data'] = sanitize_text_field( wp_unslash( $_REQUEST['s'] ) ); // Input var okay.
82
			$track['code'] = 'search';
83
		}
84
85
		if ( ! empty( $track ) ) {
86
			$track['url'] = $this->_get_url( $track );
87
			// adjust the code that we output, account for both types of tracking.
88
			$track['url'] = esc_js( str_replace( '&', '&amp;', $track['url'] ) );
89
			$custom_vars[] = "_gaq.push(['_trackPageview','{$track['url']}']);";
90
		} else {
91
			$custom_vars[] = "_gaq.push(['_trackPageview']);";
92
		}
93
94
		/**
95
		 * Allow for additional elements to be added to the classic Google Analytics queue (_gaq) array
96
		 *
97
		 * @since 5.4.0
98
		 *
99
		 * @param array $custom_vars Array of classic Google Analytics queue elements
100
		 */
101
		$custom_vars = apply_filters( 'jetpack_wga_classic_custom_vars', $custom_vars );
102
103
		// Ref: https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce#Example
104
		$async_code = "<!-- Jetpack Google Analytics -->
105
			<script type='text/javascript'>
106
				var _gaq = _gaq || [];
107
				%custom_vars%
108
109
				(function() {
110
					var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
111
					ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
112
					var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
113
				})();
114
			</script>";
115
116
		$custom_vars_string = implode( "\r\n", $custom_vars );
117
		$async_code = str_replace( '%custom_vars%', $custom_vars_string, $async_code );
118
119
		echo "$async_code\r\n";
120
	}
121
122
	/**
123
	 * Used to filter in the anonymize IP snippet to the custom vars array for classic analytics
124
	 * Ref https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApi_gat#_gat._anonymizelp
125
	 * @param array custom vars to be filtered
126
	 * @return array possibly updated custom vars
127
	 */
128
	public function jetpack_wga_classic_anonymize_ip( $custom_vars ) {
129
		if ( Jetpack_Google_Analytics_Options::anonymize_ip_is_enabled() ) {
130
			array_push( $custom_vars, "_gaq.push(['_gat._anonymizeIp']);" );
131
		}
132
133
		return $custom_vars;
134
	}
135
136
	/**
137
	 * Used to filter in the order details to the custom vars array for classic analytics
138
	 * @param array custom vars to be filtered
139
	 * @return array possibly updated custom vars
140
	 */
141
	public function jetpack_wga_classic_track_purchases( $custom_vars ) {
142
		global $wp;
143
144
		if ( ! class_exists( 'WooCommerce' ) ) {
145
			return $custom_vars;
146
		}
147
148
		if ( ! Jetpack_Google_Analytics_Options::has_tracking_code() ) {
149
			return;
150
		}
151
152
		// Ref: https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce#Example
153
		if ( ! Jetpack_Google_Analytics_Options::track_purchases_is_enabled() ) {
154
			return $custom_vars;
155
		}
156
157
		$minimum_woocommerce_active = class_exists( 'WooCommerce' ) && version_compare( WC_VERSION, '3.0', '>=' );
158
		if ( $minimum_woocommerce_active && is_order_received_page() ) {
159
			$order_id = isset( $wp->query_vars['order-received'] ) ? $wp->query_vars['order-received'] : 0;
160
			if ( 0 < $order_id && 1 != get_post_meta( $order_id, '_ga_tracked', true ) ) {
161
				$order = new WC_Order( $order_id );
162
163
				// [ '_add_Trans', '123', 'Site Title', '21.00', '1.00', '5.00', 'Snohomish', 'WA', 'USA' ]
164
				array_push(
165
					$custom_vars,
166
					sprintf(
167
						'_gaq.push( %s );', json_encode(
168
							array(
169
								'_addTrans',
170
								(string) $order->get_order_number(),
171
								get_bloginfo( 'name' ),
172
								(string) $order->get_total(),
173
								(string) $order->get_total_tax(),
174
								(string) $order->get_total_shipping(),
175
								(string) $order->get_billing_city(),
176
								(string) $order->get_billing_state(),
177
								(string) $order->get_billing_country()
178
							)
179
						)
180
					)
181
				);
182
183
				// Order items
184
				if ( $order->get_items() ) {
185
					foreach ( $order->get_items() as $item ) {
186
						$product = $order->get_product_from_item( $item );
187
						$product_sku_or_id = $product->get_sku() ? $product->get_sku() : $product->get_id();
188
189
						array_push(
190
							$custom_vars,
191
							sprintf(
192
								'_gaq.push( %s );', json_encode(
193
									array(
194
										'_addItem',
195
										(string) $order->get_order_number(),
196
										(string) $product_sku_or_id,
197
										$item['name'],
198
										self::get_product_categories_concatenated( $product ),
199
										(string) $order->get_item_total( $item ),
200
										(string) $item['qty']
201
									)
202
								)
203
							)
204
						);
205
					}
206
				} // get_items
207
208
				// Mark the order as tracked
209
				update_post_meta( $order_id, '_ga_tracked', 1 );
210
				array_push( $custom_vars, "_gaq.push(['_trackTrans']);" );
211
			} // order not yet tracked
212
		} // is order received page
213
214
		return $custom_vars;
215
	}
216
217
	/**
218
	 * Gets product categories or varation attributes as a formatted concatenated string
219
	 * @param WC_Product
220
	 * @return string
221
	 */
222
	public function get_product_categories_concatenated( $product ) {
223
		$variation_data = $product->is_type( 'variation' ) ? wc_get_product_variation_attributes( $product->get_id() ) : '';
224
		if ( is_array( $variation_data ) && ! empty( $variation_data ) ) {
225
			$line = wc_get_formatted_variation( $variation_data, true );
226
		} else {
227
			$out = array();
228
			$categories = get_the_terms( $product->get_id(), 'product_cat' );
229
			if ( $categories ) {
230
				foreach ( $categories as $category ) {
231
					$out[] = $category->name;
232
				}
233
			}
234
			$line = join( "/", $out );
235
		}
236
		return $line;
237
	}
238
239
	/**
240
	 * Used to add footer javascript to track user clicking on add-to-cart buttons
241
	 * on single views (.single_add_to_cart_button) and list views (.add_to_cart_button)
242
	 */
243
	public function jetpack_wga_classic_track_add_to_cart() {
244
		if ( ! class_exists( 'WooCommerce' ) ) {
245
			return;
246
		}
247
248
		if ( ! Jetpack_Google_Analytics_Options::has_tracking_code() ) {
249
			return;
250
		}
251
252
		if ( ! Jetpack_Google_Analytics_Options::track_add_to_cart_is_enabled() ) {
253
			return;
254
		}
255
256
		if ( is_product() ) { // product page
257
			global $product;
258
			$product_sku_or_id = $product->get_sku() ? $product->get_sku() : "#" + $product->get_id();
259
			wc_enqueue_js(
260
				"jQuery( function( $ ) {
261
					$( '.single_add_to_cart_button' ).click( function() {
262
						_gaq.push(['_trackEvent', 'Products', 'Add to Cart', '#" . esc_js( $product_sku_or_id ) . "']);
263
					} );
264
				} );"
265
			);
266
		} else if ( is_woocommerce() ) { // any other page that uses templates (like product lists, archives, etc)
267
			wc_enqueue_js(
268
				"jQuery( function( $ ) {
269
					$( '.add_to_cart_button:not(.product_type_variable, .product_type_grouped)' ).click( function() {
270
						var label = $( this ).data( 'product_sku' ) ? $( this ).data( 'product_sku' ) : '#' + $( this ).data( 'product_id' );
271
						_gaq.push(['_trackEvent', 'Products', 'Add to Cart', label]);
272
					} );
273
				} );"
274
			);
275
		}
276
	}
277
}