-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathwp-google-analytics.php
582 lines (515 loc) · 20.9 KB
/
wp-google-analytics.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
<?php
/**
* Plugin Name: WP Google Analytics
* Plugin URI: http://bluedogwebservices.com/wordpress-plugin/wp-google-analytics/
* Description: Lets you use <a href="http://analytics.google.com">Google Analytics</a> to track your WordPress site statistics
* Version: 1.4.1
* Author: Aaron D. Campbell
* Author URI: http://ran.ge/
* License: GPLv2 or later
* Text Domain: wp-google-analytics
*/
define('WGA_VERSION', '1.4.1');
/* Copyright 2006 Aaron D. Campbell (email : [email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
* wpGoogleAnalytics is the class that handles ALL of the plugin functionality.
* It helps us avoid name collisions
* http://codex.wordpress.org/Writing_a_Plugin#Avoiding_Function_Name_Collisions
*/
class wpGoogleAnalytics {
/**
* @var wpGoogleAnalytics - Static property to hold our singleton instance
*/
static $instance = false;
static $page_slug = 'wp-google-analytics';
var $tokens = array();
/**
* This is our constructor, which is private to force the use of get_instance()
* @return void
*/
private function __construct() {
add_filter( 'init', array( $this, 'init' ) );
add_action( 'admin_init', array( $this, 'admin_init' ) );
add_action( 'admin_menu', array( $this, 'admin_menu' ) );
add_action( 'get_footer', array( $this, 'insert_code' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'track_outgoing' ) );
add_filter( 'plugin_action_links', array( $this, 'add_plugin_page_links' ), 10, 2 );
}
/**
* Function to instantiate our class and make it a singleton
*/
public static function get_instance() {
if ( !self::$instance )
self::$instance = new self;
return self::$instance;
}
public function init() {
load_plugin_textdomain( 'wp-google-analytics', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
$this->tokens = array(
array(
'token' => '%the_author%',
'callback' => 'get_the_author',
'callback_returns' => 'string',
'description' => __( 'Post author for current view', 'wp-google-analytics' ),
'retval' => __( "Post author's display name", 'wp-google-analytics' ),
'ignore_when' => array(
'is_home',
'is_front_page',
'is_post_type_archive',
'is_page',
'is_date',
'is_category',
'is_tag',
),
),
array(
'token' => '%the_category%',
'callback' => array( $this, 'token_the_category' ),
'callback_returns' => 'string',
'description' => __( 'Categories assigned to a post', 'wp-google-analytics' ),
'retval' => __( "Category names in a commma-separated list", 'wp-google-analytics' ),
'ignore_when' => array(
'is_home',
'is_front_page',
'is_page',
'is_post_type_archive',
'is_author',
'is_tag',
),
),
array(
'token' => '%context%',
'callback' => array( $this, 'token_context' ),
'callback_returns' => 'string',
'description' => __( 'Which view the visitor is on', 'wp-google-analytics' ),
'retval' => __( "Samples: 'home', 'category', 'post', 'author'" ),
),
array(
'token' => '%the_date%',
'callback' => 'get_the_date',
'callback_returns' => 'string',
'description' => __( 'Publication date for the current view', 'wp-google-analytics' ),
'retval' => __( "Format specified by 'Date Format' in Settings -> General", 'wp-google-analytics' ),
'ignore_when' => array(
'is_home',
'is_front_page',
'is_post_type_archive',
'is_page',
'is_author',
'is_category',
'is_tag',
),
),
array(
'token' => '%the_tags%',
'callback' => array( $this, 'token_the_tags' ),
'callback_returns' => 'string',
'description' => __( 'Tags assigned to a post', 'wp-google-analytics' ),
'retval' => __( "Tag names in a commma-separated list", 'wp-google-analytics' ),
'ignore_when' => array(
'is_home',
'is_front_page',
'is_page',
'is_post_type_archive',
'is_date',
'is_category',
'is_author',
),
),
array(
'token' => '%is_user_logged_in%',
'callback' => 'is_user_logged_in',
'callback_returns' => 'bool',
'description' => __( 'Whether or not the viewer is logged in', 'wp-google-analytics' ),
'retval' => __( "'true' or 'false'", 'wp-google-analytics' ),
),
);
$this->tokens = apply_filters( 'wga_tokens', $this->tokens );
}
/**
* This adds the options page for this plugin to the Options page
*/
public function admin_menu() {
add_options_page(__('Google Analytics', 'wp-google-analytics'), __('Google Analytics', 'wp-google-analytics'), 'manage_options', self::$page_slug, array( $this, 'settings_view' ) );
}
/**
* Register our settings
*/
public function admin_init() {
register_setting( 'wga', 'wga', array( $this, 'sanitize_general_options' ) );
add_settings_section( 'wga_general', false, '__return_false', 'wga' );
add_settings_field( 'code', __( 'Google Analytics tracking ID:', 'wp-google-analytics' ), array( $this, 'field_code' ), 'wga', 'wga_general' );
add_settings_field( 'additional_items', __( 'Additional items to log:', 'wp-google-analytics' ), array( $this, 'field_additional_items' ), 'wga', 'wga_general' );
add_settings_field( 'do_not_track', __( 'Visits to ignore:', 'wp-google-analytics' ), array( $this, 'field_do_not_track' ), 'wga', 'wga_general' );
add_settings_field( 'custom_vars', __( 'Custom variables:', 'wp-google-analytics' ), array( $this, 'field_custom_variables' ), 'wga', 'wga_general' );
}
/**
* Where the user adds their Google Analytics code
*/
public function field_code() {
// Display the tokens in the right column of the page
echo '<div id="tokens-description" style="position:absolute;margin-left:600px;margin-right:50px;">';
echo '<span>' . __( 'Use tokens in your custom variables to make your fields dynamic based on context. Here are some of the tokens you can use:' ) . '</span>';
echo '<table style="text-align:left;">';
echo '<thead><tr><td>' . __( 'Token', 'wp-google-analytics' ) . '</td><td>' . __( 'Description', 'wp-google-analytics' ) . '</td><td>' . __( 'Return value', 'wp-google-analytics' ) . '</td></tr></thead>';
echo '<tbody>';
foreach( $this->tokens as $token ) {
echo '<tr>';
echo '<td>' . esc_html( $token['token'] ) . '</td>';
echo '<td>' . esc_html( $token['description'] ) . '</td>';
echo '<td>' . esc_html( $token['retval'] ) . '</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
echo '</div>';
echo '<input name="wga[code]" id="wga-code" type="text" value="' . esc_attr( $this->_get_options( 'code' ) ) . '" />';
echo '<p class="description">' . __( 'Paste your Google Analytics tracking ID (e.g. "UA-XXXXXX-X") into the field.', 'wp-google-analytics' ) . '</p>';
}
/**
* Option to log additional items
*/
public function field_additional_items() {
$addtl_items = array(
'log_404s' => __( 'Log 404 errors as events', 'wp-google-analytics' ),
'log_searches' => sprintf( __( 'Log searches as /search/{search}?referrer={referrer} (<a href="%s">deprecated</a>)', 'wp-google-analytics' ), 'http://wordpress.org/extend/plugins/wp-google-analytics/faq/' ),
'log_outgoing' => __( 'Log outgoing links as events', 'wp-google-analytics' ),
);
foreach( $addtl_items as $id => $label ) {
echo '<label for="wga_' . $id . '">';
echo '<input id="wga_' . $id . '" type="checkbox" name="wga[' . $id . ']" value="true" ' . checked( 'true', $this->_get_options( $id ), false ) . ' />';
echo ' ' . $label;
echo '</label><br />';
}
}
/**
* Define custom variables to be included in your tracking code
*/
public function field_custom_variables() {
$custom_vars = $this->_get_options( 'custom_vars' );
$scope_options = array(
0 => __( 'Default', 'wp-google-analytics' ),
1 => __( 'Visitor', 'wp-google-analytics' ),
2 => __( 'Session', 'wp-google-analytics' ),
3 => __( 'Page', 'wp-google-analytics' ),
);
for ( $i = 1; $i <= 5; $i++ ) {
$name = ( isset( $custom_vars[$i]['name'] ) ) ? $custom_vars[$i]['name'] : '';
$value = ( isset( $custom_vars[$i]['value'] ) ) ? $custom_vars[$i]['value'] : '';
$scope = ( isset( $custom_vars[$i]['scope'] ) ) ? $custom_vars[$i]['scope'] : 0;
echo '<label for="wga_custom_var_' . $i . '_name"><strong>' . $i . ')</strong> ' . __( 'Name', 'wp-google-analytics' ) . ' ';
echo '<input id="wga_custom_var_' . $i . '" type="text" name="wga[custom_vars][' . $i . '][name]" value="' . esc_attr( $name ) . '" />';
echo '</label> ';
echo '<label for="wga_custom_var_' . $i . '_value">' . __( 'Value', 'wp-google-analytics' ) . ' ';
echo '<input id="wga_custom_var_' . $i . '" type="text" name="wga[custom_vars][' . $i . '][value]" value="' . esc_attr( $value ) . '" />';
echo '</label> ';
echo '<label for="wga_custom_var_' . $i . '_scope">' . __( 'Scope', 'wp-google-analytics' ) . ' ';
echo '<select id="wga_custom_var_' . $i . '_scope" name="wga[custom_vars][' . $i . '][scope]">';
foreach( $scope_options as $key => $label ) {
echo '<option value="' . $key . '" ' . selected( $scope, $key, false ) . '>';
echo $label . '</option>';
}
echo '</select>';
echo '</label><br />';
}
}
public function field_do_not_track() {
$do_not_track = array(
'ignore_admin_area' => __( 'Do not log anything in the admin area', 'wp-google-analytics' ),
);
global $wp_roles;
foreach( $wp_roles->roles as $role => $role_info ) {
$do_not_track['ignore_role_' . $role] = sprintf( __( 'Do not log %s when logged in', 'wp-google-analytics' ), rtrim( $role_info['name'], 's' ) );
}
foreach( $do_not_track as $id => $label ) {
echo '<label for="wga_' . $id . '">';
echo '<input id="wga_' . $id . '" type="checkbox" name="wga[' . $id . ']" value="true" ' . checked( 'true', $this->_get_options( $id ), false ) . ' />';
echo ' ' . $label;
echo '</label><br />';
}
}
/**
* Sanitize all of the options associated with the plugin
*/
public function sanitize_general_options( $in ) {
$out = array();
// The actual tracking ID
if ( preg_match( '#UA-[\d-]+#', $in['code'], $matches ) )
$out['code'] = $matches[0];
else
$out['code'] = '';
$checkbox_items = array(
// Additional items you can track
'log_404s',
'log_searches',
'log_outgoing',
// Things to ignore
'ignore_admin_area',
);
global $wp_roles;
foreach( $wp_roles->roles as $role => $role_info ) {
$checkbox_items[] = 'ignore_role_' . $role;
}
foreach( $checkbox_items as $checkbox_item ) {
if ( isset( $in[$checkbox_item] ) && 'true' == $in[$checkbox_item] )
$out[$checkbox_item] = 'true';
else
$out[$checkbox_item] = 'false';
}
// Custom variables
for( $i = 1; $i <= 5; $i++ ) {
foreach( array( 'name', 'value', 'scope' ) as $key ) {
if ( isset( $in['custom_vars'][$i][$key] ) )
$out['custom_vars'][$i][$key] = sanitize_text_field( $in['custom_vars'][$i][$key] );
else
$out['custom_vars'][$i][$key] = '';
}
}
return $out;
}
/**
* This is used to display the options page for this plugin
*/
public function settings_view() {
?>
<div class="wrap">
<h2><?php _e('Google Analytics Options', 'wp-google-analytics') ?></h2>
<form action="options.php" method="post" id="wp_google_analytics">
<?php
settings_fields( 'wga' );
do_settings_sections( 'wga' );
submit_button( __( 'Update Options', 'wp-google-analytics' ) );
?>
</form>
</div>
<?php
}
/**
* Used to generate a tracking URL
*
* @param array $track - Must have ['data'] and ['code']
* @return string - Tracking URL
*/
private function _get_url($track) {
$site_url = ( is_ssl() ? 'https://':'http://' ).$_SERVER['HTTP_HOST'];
foreach ($track as $k=>$value) {
if (strpos(strtolower($value), strtolower($site_url)) === 0) {
$track[$k] = substr($track[$k], strlen($site_url));
}
if ($k == 'data') {
$track[$k] = preg_replace("/^https?:\/\/|^\/+/i", "", $track[$k]);
}
//This way we don't lose search data.
if ($k == 'data' && $track['code'] == 'search') {
$track[$k] = urlencode($track[$k]);
} else {
$track[$k] = preg_replace("/[^a-z0-9\.\/\+\?=-]+/i", "_", $track[$k]);
}
$track[$k] = trim($track[$k], '_');
}
$char = (strpos($track['data'], '?') === false)? '?':'&';
return str_replace("'", "\'", "/{$track['code']}/{$track['data']}{$char}referer=" . urlencode( isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : '' ) );
}
/**
* Maybe output or return, depending on the context
*/
private function _output_or_return( $val, $maybe ) {
if ( $maybe )
echo $val . "\r\n";
else
return $val;
}
/**
* This injects the Google Analytics code into the footer of the page.
*
* @param bool[optional] $output - defaults to true, false returns but does NOT echo the code
*/
public function insert_code( $output = true ) {
//If $output is not a boolean false, set it to true (default)
$output = ($output !== false);
$tracking_id = $this->_get_options( 'code' );
if ( empty( $tracking_id ) )
return $this->_output_or_return( '<!-- Your Google Analytics Plugin is missing the tracking ID -->', $output );
//get our plugin options
$wga = $this->_get_options();
//If the user's role has wga_no_track set to true, return without inserting code
if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
$role = array_shift( $current_user->roles );
if ( 'true' == $this->_get_options( 'ignore_role_' . $role ) )
return $this->_output_or_return( "<!-- Google Analytics Plugin is set to ignore your user role -->", $output );
}
//If $admin is true (we're in the admin_area), and we've been told to ignore_admin_area, return without inserting code
if (is_admin() && (!isset($wga['ignore_admin_area']) || $wga['ignore_admin_area'] != 'false'))
return $this->_output_or_return( "<!-- Your Google Analytics Plugin is set to ignore Admin area -->", $output );
$custom_vars = array(
"_gaq.push(['_setAccount', '{$tracking_id}']);",
);
// Add custom variables specified by the user
foreach( $this->_get_options( 'custom_vars', array() ) as $i => $custom_var ) {
if ( empty( $custom_var['name'] ) || empty( $custom_var['value'] ) )
continue;
// Check whether a token was used with this custom var, and replace with value if so
$all_tokens = wp_list_pluck( $this->tokens, 'token' );
if ( in_array( $custom_var['value'], $all_tokens ) ) {
$token = array_pop( wp_filter_object_list( $this->tokens, array( 'token' => $custom_var['value'] ) ) );
// Allow tokens to return empty values for specific contexts
$ignore = false;
if ( ! empty( $token['ignore_when'] ) ) {
foreach( (array)$token['ignore_when'] as $conditional ) {
if ( is_callable( $conditional ) ) {
$ignore = call_user_func( $conditional );
if ( $ignore )
break;
}
}
}
// If we aren't set to ignore this context, possibly execute the callback
if ( ! $ignore && ! empty( $token['callback'] ) && is_callable( $token['callback'] ) )
$replace = call_user_func( $token['callback'] );
else
$replace = '';
if ( ! empty( $token['callback_returns'] ) && 'bool' == $token['callback_returns'] )
$replace = ( $replace ) ? 'true' : 'false';
// Replace our token with the value
$custom_var['value'] = str_replace( $custom_var['value'], $replace, $custom_var['value'] );
}
$atts = array(
"'_setCustomVar'",
intval( $i ),
"'" . esc_js( $custom_var['name'] ) . "'",
"'" . esc_js( $custom_var['value'] ) . "'",
);
if ( $custom_var['scope'] )
$atts[] = intval( $custom_var['scope'] );
$custom_vars[] = "_gaq.push([" . implode( ', ', $atts ) . "]);";
}
$track = array();
if (is_404() && (!isset($wga['log_404s']) || $wga['log_404s'] != 'false')) {
// This is a 404 and we are supposed to track them
$custom_vars[] = "_gaq.push( [ '_trackEvent', '404', document.location.href, document.referrer ] );";
} elseif (is_search() && (!isset($wga['log_searches']) || $wga['log_searches'] != 'false')) {
//Set track for searches, if it's a search, and we are supposed to
$track['data'] = $_REQUEST['s'];
$track['code'] = "search";
}
if ( ! empty( $track ) ) {
$track['url'] = $this->_get_url( $track );
//adjust the code that we output, account for both types of tracking
$track['url'] = esc_js( str_replace( '&', '&', $track['url'] ) );
$custom_vars[] = "_gaq.push(['_trackPageview','{$track['url']}']);";
} else {
$custom_vars[] = "_gaq.push(['_trackPageview']);";
}
$async_code = "<script type='text/javascript'>
var _gaq = _gaq || [];
%custom_vars%
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>";
$custom_vars_string = implode( "\r\n", $custom_vars );
$async_code = str_replace( '%custom_vars%', $custom_vars_string, $async_code );
return $this->_output_or_return( $async_code, $output );
}
/**
* Used to get one or all of our plugin options
*
* @param string[optional] $option - Name of options you want. Do not use if you want ALL options
* @return array of options, or option value
*/
private function _get_options( $option = null, $default = false ) {
$o = get_option('wga');
if (isset($option)) {
if (isset($o[$option])) {
if ( 'code' == $option ) {
if ( preg_match( '#UA-[\d-]+#', $o[$option], $matches ) )
return $matches[0];
else
return '';
} else
return $o[$option];
} else {
if ( 'ignore_role_' == substr( $option, 0, 12 ) ) {
global $wp_roles;
// Backwards compat for when the tracking information was stored as a cap
$maybe_role = str_replace( 'ignore_role_', '', $option );
if ( isset( $wp_roles->roles[$maybe_role] ) ) {
if ( isset( $wp_roles->roles[$maybe_role]['capabilities']['wga_no_track'] ) && $wp_roles->roles[$maybe_role]['capabilities']['wga_no_track'] )
return 'true';
}
return false;
}
return $default;
}
} else {
return $o;
}
}
/**
* If we track outgoing links, this will enqueue our javascript file
*/
public function track_outgoing() {
if ( 'true' == $this->_get_options( 'log_outgoing' ) && (!defined('XMLRPC_REQUEST') || !XMLRPC_REQUEST) && ( ! is_admin() || 'false' == $this->_get_options( 'ignore_admin_area' ) ) )
wp_enqueue_script( 'wp-google-analytics', plugin_dir_url( __FILE__ ) . 'wp-google-analytics.js', array( 'jquery' ), '0.0.3' );
}
/**
* Callback for %the_category% token
*/
public function token_the_category() {
return implode( ', ', wp_list_pluck( (array)get_the_category(), 'name' ) );
}
/**
* Callback for %context% token
*/
public function token_context() {
if ( is_admin() ) {
return 'admin';
} else if ( is_home() || is_front_page() ) {
return 'home';
} else if ( is_tax() || is_tag() || is_category() ) {
return get_queried_object()->taxonomy;
} else if ( is_author() ) {
return 'author';
} else if ( is_singular() || is_single() || is_page() ) {
return get_post_type();
} else if ( is_search() ) {
return 'search';
} else if ( is_date() ) {
return 'date';
} else if ( is_archive() ) {
return 'archive';
} else if ( is_404() ) {
return '404';
}
}
/**
* Callback for %the_tags% token
*/
public function token_the_tags() {
return implode( ', ', wp_list_pluck( (array)get_the_tags(), 'name' ) );
}
public function add_plugin_page_links( $links, $file ){
if ( plugin_basename( __FILE__ ) == $file ) {
$link = '<a href="' . admin_url( 'options-general.php?page=' . self::$page_slug ) . '">' . __( 'Settings', 'wp-google-analytics' ) . '</a>';
array_unshift( $links, $link );
}
return $links;
}
}
global $wp_google_analytics;
$wp_google_analytics = wpGoogleAnalytics::get_instance();