WP Google Analytics - Version 1.3.0

Version Description

Move to using events for tracking 404s and outgoing links and add support for custom variables

=

Download this release

Release Info

Developer aaroncampbell
Plugin Icon wp plugin WP Google Analytics
Version 1.3.0
Comparing to
See all releases

Code changes from version 1.2.5 to 1.3.0

languages/wp-google-analytics.pot ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (C) 2012 WP Google Analytics
2
+ # This file is distributed under the same license as the WP Google Analytics package.
3
+ msgid ""
4
+ msgstr ""
5
+ "Project-Id-Version: WP Google Analytics 1.3.0\n"
6
+ "Report-Msgid-Bugs-To: http://wordpress.org/tag/wp-google-analytics\n"
7
+ "POT-Creation-Date: 2012-10-01 18:55:47+00:00\n"
8
+ "MIME-Version: 1.0\n"
9
+ "Content-Type: text/plain; charset=UTF-8\n"
10
+ "Content-Transfer-Encoding: 8bit\n"
11
+ "PO-Revision-Date: 2012-MO-DA HO:MI+ZONE\n"
12
+ "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
13
+ "Language-Team: LANGUAGE <LL@li.org>\n"
14
+
15
+ #: wp-google-analytics.php:76
16
+ msgid "Google Analytics"
17
+ msgstr ""
18
+
19
+ #: wp-google-analytics.php:86
20
+ msgid "Google Analytics tracking ID:"
21
+ msgstr ""
22
+
23
+ #: wp-google-analytics.php:87
24
+ msgid "Additional items to log:"
25
+ msgstr ""
26
+
27
+ #: wp-google-analytics.php:88
28
+ msgid "Visits to ignore:"
29
+ msgstr ""
30
+
31
+ #: wp-google-analytics.php:89
32
+ msgid "Custom variables:"
33
+ msgstr ""
34
+
35
+ #: wp-google-analytics.php:97
36
+ msgid ""
37
+ "Paste your Google Analytics tracking ID (e.g. \"UA-XXXXXX-X\") into the "
38
+ "field."
39
+ msgstr ""
40
+
41
+ #: wp-google-analytics.php:105
42
+ msgid "Log 404 errors as events"
43
+ msgstr ""
44
+
45
+ #: wp-google-analytics.php:106
46
+ msgid ""
47
+ "Log searches as /search/{search}?referrer={referrer} (<a href=\"%s"
48
+ "\">deprecated</a>)"
49
+ msgstr ""
50
+
51
+ #: wp-google-analytics.php:107
52
+ msgid "Log outgoing links as events"
53
+ msgstr ""
54
+
55
+ #: wp-google-analytics.php:124
56
+ msgid "Default"
57
+ msgstr ""
58
+
59
+ #: wp-google-analytics.php:125
60
+ msgid "Visitor"
61
+ msgstr ""
62
+
63
+ #: wp-google-analytics.php:126
64
+ msgid "Session"
65
+ msgstr ""
66
+
67
+ #: wp-google-analytics.php:127
68
+ msgid "Page"
69
+ msgstr ""
70
+
71
+ #: wp-google-analytics.php:133
72
+ msgid "Name"
73
+ msgstr ""
74
+
75
+ #: wp-google-analytics.php:136
76
+ msgid "Value"
77
+ msgstr ""
78
+
79
+ #: wp-google-analytics.php:139
80
+ msgid "Scope"
81
+ msgstr ""
82
+
83
+ #: wp-google-analytics.php:152
84
+ msgid "Do not log anything in the admin area"
85
+ msgstr ""
86
+
87
+ #: wp-google-analytics.php:156
88
+ msgid "Do not log %s when logged in"
89
+ msgstr ""
90
+
91
+ #: wp-google-analytics.php:217
92
+ msgid "Google Analytics Options"
93
+ msgstr ""
94
+
95
+ #: wp-google-analytics.php:222
96
+ msgid "Update Options"
97
+ msgstr ""
98
+
99
+ #. Plugin Name of the plugin/theme
100
+ msgid "WP Google Analytics"
101
+ msgstr ""
102
+
103
+ #. Plugin URI of the plugin/theme
104
+ msgid "http://bluedogwebservices.com/wordpress-plugin/wp-google-analytics/"
105
+ msgstr ""
106
+
107
+ #. Description of the plugin/theme
108
+ msgid ""
109
+ "Lets you use <a href=\"http://analytics.google.com\">Google Analytics</a> to "
110
+ "track your WordPress site statistics"
111
+ msgstr ""
112
+
113
+ #. Author of the plugin/theme
114
+ msgid "Aaron D. Campbell"
115
+ msgstr ""
116
+
117
+ #. Author URI of the plugin/theme
118
+ msgid "http://ran.ge/"
119
+ msgstr ""
readme.txt CHANGED
@@ -2,9 +2,9 @@
2
  Contributors: aaroncampbell
3
  Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=CLXNQ3DVK6M48
4
  Tags: analytics, google, google analytics
5
- Requires at least: 1.5
6
  Tested up to: 3.5
7
- Stable tag: 1.2.5
8
 
9
  Lets you use <a href="http://analytics.google.com">Google Analytics</a> to track your WordPress site statistics
10
 
@@ -14,10 +14,10 @@ Lets you use <a href="http://analytics.google.com">Google Analytics</a> to track
14
  your WordPress site statistics. It is easily configurable to:
15
 
16
  * Not log anything in the admin area
17
- * Log 404 errors as /404/{url}?referrer={referrer}
18
- * Log searches as /search/{search}?referrer={referrer}
19
- * Log outgoing links as /outgoing/{url}?referrer={referrer}
20
  * Not log any user roles (administrators, editors, authors, etc)
 
21
 
22
  == Installation ==
23
 
@@ -31,6 +31,15 @@ WP Google Analytics has a config page under the settings tab in the admin area
31
  of your site. You can paste your tracking code from Google into the textarea on
32
  this page.
33
 
 
 
 
 
 
 
 
 
 
34
  = Can't I just paste the Google Analytics code into my template file? =
35
 
36
  Absolutely, however in order to get a better idea of what is going on with your
@@ -38,9 +47,22 @@ site, it is often nice to have your own activities ignored, track 404s, searches
38
  and even where users go when they leave your site. WP Google Analytics lets you
39
  easily do all these things.
40
 
 
 
 
 
41
 
42
  == Changelog ==
43
 
 
 
 
 
 
 
 
 
 
44
  = 1.2.5 =
45
  * Fixed some notices. Props westi
46
  * Update all links
2
  Contributors: aaroncampbell
3
  Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=CLXNQ3DVK6M48
4
  Tags: analytics, google, google analytics
5
+ Requires at least: 3.1
6
  Tested up to: 3.5
7
+ Stable tag: 1.3.0
8
 
9
  Lets you use <a href="http://analytics.google.com">Google Analytics</a> to track your WordPress site statistics
10
 
14
  your WordPress site statistics. It is easily configurable to:
15
 
16
  * Not log anything in the admin area
17
+ * Log 404 errors as events
18
+ * Log outgoing links as events
 
19
  * Not log any user roles (administrators, editors, authors, etc)
20
+ * Use custom variables
21
 
22
  == Installation ==
23
 
31
  of your site. You can paste your tracking code from Google into the textarea on
32
  this page.
33
 
34
+ = How do I track searches? =
35
+
36
+ WP Google Analytics used to help you track site searches before Google Analytics
37
+ started doing this natively. While we still support tracking searches for
38
+ backwards compatibility, this feature has been deprecated and will eventually be
39
+ removed. To track searches in Google Analytics follow this
40
+ <a href="http://support.google.com/analytics/bin/answer.py?hl=en&answer=1012264">Google support article</a>.
41
+ WordPress uses 's' as the query parameter.
42
+
43
  = Can't I just paste the Google Analytics code into my template file? =
44
 
45
  Absolutely, however in order to get a better idea of what is going on with your
47
  and even where users go when they leave your site. WP Google Analytics lets you
48
  easily do all these things.
49
 
50
+ == Upgrade Notice ==
51
+
52
+ = 1.3.0 =
53
+ Move to using events for tracking 404s and outgoing links and add support for custom variables
54
 
55
  == Changelog ==
56
 
57
+ = 1.3.0 =
58
+ * Refactored to use settings API - Props danielbachhuber
59
+ * Convert to singleton and instatiate class
60
+ * Convert tracking code field to ID, keeping backwards compat - Props danielbachhuber
61
+ * Custom variable support - Props danielbachhuber
62
+ * Track outgoing links and 404s as events
63
+ * Made the whole plugin translatable
64
+ * Deprecated tracking searches
65
+
66
  = 1.2.5 =
67
  * Fixed some notices. Props westi
68
  * Update all links
wp-google-analytics.js ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ (function($){ // Open closure and map jQuery to $.
2
+
3
+ // Adds :external for grabbing external links
4
+ $.expr[':'].external = function(obj) {
5
+ return !obj.href.match(/^mailto\:/) && !obj.href.match(/^javascript\:/) && (obj.hostname != location.hostname);
6
+ };
7
+
8
+ // Document ready.
9
+ $( function() {
10
+ // Add 'external' class and _blank target to all external links
11
+ $('a:external').on( 'click.wp-google-analytics', function(e){
12
+ try {
13
+ _gaq.push( [ '_trackEvent', 'Outbound Links', e.currentTarget.host, $(this).attr('href') ] );
14
+ /**
15
+ * If this link is not opened in a new tab or window, we need to add
16
+ * a small delay so the event can fully fire. See:
17
+ * http://support.google.com/analytics/bin/answer.py?hl=en&answer=1136920
18
+ *
19
+ * We're actually checking for modifier keys or middle-click
20
+ */
21
+ if ( ! ( e.metaKey || e.ctrlKey || 1 == e.button ) ) {
22
+ e.preventDefault();
23
+ setTimeout('document.location = "' + $(this).attr('href') + '"', 100)
24
+ }
25
+ } catch(err) {}
26
+ });
27
+ });
28
+
29
+ })( jQuery ); // Close closure.
wp-google-analytics.php CHANGED
@@ -3,12 +3,14 @@
3
  * Plugin Name: WP Google Analytics
4
  * Plugin URI: http://bluedogwebservices.com/wordpress-plugin/wp-google-analytics/
5
  * Description: Lets you use <a href="http://analytics.google.com">Google Analytics</a> to track your WordPress site statistics
6
- * Version: 1.2.5
7
  * Author: Aaron D. Campbell
8
  * Author URI: http://ran.ge/
 
 
9
  */
10
 
11
- define('WGA_VERSION', '1.2.5');
12
 
13
  /* Copyright 2006 Aaron D. Campbell (email : wp_plugins@xavisys.com)
14
 
@@ -27,10 +29,6 @@ define('WGA_VERSION', '1.2.5');
27
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28
  */
29
 
30
- //If this is set to true, extra info will be dumped to the browser.
31
- //ONLY do this if you really need it
32
- define('WGA_DEBUG', false);
33
-
34
  /**
35
  * wpGoogleAnalytics is the class that handles ALL of the plugin functionality.
36
  * It helps us avoid name collisions
@@ -38,75 +36,191 @@ define('WGA_DEBUG', false);
38
  */
39
  class wpGoogleAnalytics {
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  /**
42
  * This adds the options page for this plugin to the Options page
43
  */
44
- function admin_menu() {
45
- add_options_page(__('Google Analytics'), __('Google Analytics'), 'manage_options', str_replace("\\", "/", __FILE__), array('wpGoogleAnalytics', 'options'));
46
  }
47
 
48
  /**
49
- * This is used to display the options page for this plugin
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  */
51
- function options() {
52
- /**
53
- * @var WP_Roles
54
- */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  global $wp_roles;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
- //Get our options
58
- $wga = wpGoogleAnalytics::get_options();
59
- //Echo debug info if needed
60
- if (WGA_DEBUG) {
61
- echo '<pre>',var_dump($wga),'</pre>';
 
 
 
 
 
 
 
 
 
 
 
 
62
  }
63
- //We will fill $roles with checkboxes to ignore each role
64
- $roles = '';
65
- foreach ($wp_roles->roles as $role=>$role_info) {
66
- $checked = (isset($role_info['capabilities']['wga_no_track']) && $role_info['capabilities']['wga_no_track'])? ' checked="checked"':'';
67
- $role_info['name'] .= (strtolower(substr($role_info['name'], -1)) != 's')? 's':'';
68
- $roles .= " <label for='wga_role_{$role}'><input type='checkbox' name='wga-roles[{$role}]' value='true' id='wga_role_{$role}'{$checked} /> ".__("Do not log {$role_info['name']} when logged in")."</label><br />";
 
 
 
 
 
 
 
 
 
69
  }
 
 
 
 
 
 
 
 
70
  ?>
71
  <div class="wrap">
72
- <h2><?php _e('Google Analytics Options') ?></h2>
73
  <form action="options.php" method="post" id="wp_google_analytics">
74
- <?php wp_nonce_field('update-options'); ?>
75
- <p>Google Maps for WordPress will allow you to easily add maps to your posts or pages.</p>
76
- <table class="form-table">
77
- <tr valign="top">
78
- <th scope="row">
79
- <label for="wga_code"><?php _e('Paste your <a href="http://analytics.google.com">Google Analytics</a> code into the textarea:'); ?></label>
80
- </th>
81
- <td>
82
- <textarea name="wga[code]" id="wga_code" style="width:95%;" rows="10"><?php echo htmlentities($wga['code']); ?></textarea>
83
- </td>
84
- </tr>
85
- <tr valign="top">
86
- <th scope="row">
87
- <?php _e('Additional items to log:') ?>
88
- </th>
89
- <td>
90
- <label for="wga_log_404s"><input type="checkbox" name="wga[log_404s]" value="true" id="wga_log_404s"<?php checked('true', $wga['log_404s']); ?> /> <?php _e('Log 404 errors as /404/{url}?referrer={referrer}'); ?></label><br />
91
- <label for="wga_log_searches"><input type="checkbox" name="wga[log_searches]" value="true" id="wga_log_searches"<?php checked('true', $wga['log_searches']); ?> /> <?php _e('Log searches as /search/{search}?referrer={referrer}'); ?></label><br />
92
- <label for="wga_log_outgoing"><input type="checkbox" name="wga[log_outgoing]" value="true" id="wga_log_outgoing"<?php checked('true', $wga['log_outgoing']); ?> /> <?php _e('Log outgoing links as /outgoing/{url}?referrer={referrer}'); ?></label><br />
93
- </td>
94
- </tr>
95
- <tr valign="top">
96
- <th scope="row">
97
- <?php _e('Visits to ignore:') ?>
98
- </th>
99
- <td>
100
- <label for="wga_ignore_admin_area"><input type="checkbox" name="wga[ignore_admin_area]" value="true" id="wga_ignore_admin_area"<?php checked('true', $wga['ignore_admin_area']); ?> /> <?php _e('Do not log anything in the admin area'); ?></label><br />
101
- <?php echo $roles; ?>
102
- </td>
103
- </tr>
104
- </table>
105
- <p class="submit">
106
- <input type="submit" name="Submit" value="<?php _e('Update Options &raquo;'); ?>" />
107
- </p>
108
- <input type="hidden" name="action" value="update" />
109
- <input type="hidden" name="page_options" value="wga,wga-roles" />
110
  </form>
111
  </div>
112
  <?php
@@ -118,7 +232,7 @@ class wpGoogleAnalytics {
118
  * @param array $track - Must have ['data'] and ['code']
119
  * @return string - Tracking URL
120
  */
121
- function get_url($track) {
122
  $site_url = ( is_ssl() ? 'https://':'http://' ).$_SERVER['HTTP_HOST'];
123
  foreach ($track as $k=>$value) {
124
  if (strpos(strtolower($value), strtolower($site_url)) === 0) {
@@ -141,77 +255,96 @@ class wpGoogleAnalytics {
141
  return str_replace("'", "\'", "/{$track['code']}/{$track['data']}{$char}referer=" . urlencode( isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : '' ) );
142
  }
143
 
 
 
 
 
 
 
 
 
 
 
144
  /**
145
  * This injects the Google Analytics code into the footer of the page.
146
  *
147
  * @param bool[optional] $output - defaults to true, false returns but does NOT echo the code
148
  */
149
- function insert_code($output=true) {
150
  //If $output is not a boolean false, set it to true (default)
151
  $output = ($output !== false);
152
 
 
 
 
 
153
  //get our plugin options
154
- $wga = wpGoogleAnalytics::get_options();
155
  //If the user's role has wga_no_track set to true, return without inserting code
156
- if (current_user_can('wga_no_track')) {
157
- $ret = "<!-- Google Analytics Plugin is set to ignore your user role -->\r\n";
158
- if ($output) {
159
- echo $ret;
160
- }
161
- return $ret;
162
  }
163
- //If the Google Analytics code has been set
164
- if ($wga['code'] !== false) {
165
- //Echo debug info if needed
166
- if (WGA_DEBUG) {
167
- echo '<pre>',var_dump($wga),'</pre>';
168
- }
169
 
170
- //If $admin is true (we're in the admin_area), and we've been told to ignore_admin_area, return without inserting code
171
- if (is_admin() && (!isset($wga['ignore_admin_area']) || $wga['ignore_admin_area'] != 'false')) {
172
- $ret = "<!-- Your Google Analytics Plugin is set to ignore Admin area -->\r\n";
173
- if ($output) {
174
- echo $ret;
175
- }
176
- return $ret;
177
- } elseif (is_404() && (!isset($wga['log_404s']) || $wga['log_404s'] != 'false')) {
178
- //Set track for 404s, if it's a 404, and we are supposed to
179
- $track['data'] = $_SERVER['REQUEST_URI'];
180
- $track['code'] = '404';
181
- } elseif (is_search() && (!isset($wga['log_searches']) || $wga['log_searches'] != 'false')) {
182
- //Set track for searches, if it's a search, and we are supposed to
183
- $track['data'] = $_REQUEST['s'];
184
- $track['code'] = "search";
185
- }
186
 
187
- //If we need to generate a special tracking URL
188
- if (isset($track)) {
189
- //get the tracking URL
190
- $track['url'] = wpGoogleAnalytics::get_url($track);
191
 
192
- //adjust the code that we output, account for both types of tracking
193
- $track['url'] = str_replace('&', '&amp;', $track['url']);
194
- $wga['code'] = str_replace("urchinTracker()","urchinTracker('{$track['url']}')", $wga['code']);
195
- $wga['code'] = str_replace("pageTracker._trackPageview()","pageTracker._trackPageview('{$track['url']}')", $wga['code']);
 
 
 
 
 
196
 
197
- //Echo debug info if needed
198
- if (WGA_DEBUG) {
199
- echo '<pre>',var_dump($track, $site_url),'</pre>';
200
- }
201
- }
202
- //output the Google Analytics code
203
- if ($output) {
204
- echo $wga['code'];
205
- }
206
- return $wga['code'];
207
  } else {
208
- //If the Google Analytics code has not been set in admin area, return without inserting code
209
- $ret = "<!-- You need to set up the Google Analytics Plugin -->\r\n";
210
- if ($output) {
211
- echo $ret;
212
- }
213
- return $ret;
214
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
  }
216
 
217
  /**
@@ -220,13 +353,32 @@ class wpGoogleAnalytics {
220
  * @param string[optional] $option - Name of options you want. Do not use if you want ALL options
221
  * @return array of options, or option value
222
  */
223
- function get_options($option = null) {
 
224
  $o = get_option('wga');
 
225
  if (isset($option)) {
 
226
  if (isset($o[$option])) {
227
- return $o[$option];
 
 
 
 
 
 
228
  } else {
229
- return false;
 
 
 
 
 
 
 
 
 
 
230
  }
231
  } else {
232
  return $o;
@@ -234,113 +386,15 @@ class wpGoogleAnalytics {
234
  }
235
 
236
  /**
237
- * Start our output buffering with a callback, to grab all links
238
- *
239
- * @todo If there is a good way to tell if this is a feed, add a seperate option for tracking outgoings on feeds
240
  */
241
- function start_ob() {
242
- $log_outgoing = wpGoogleAnalytics::get_options('log_outgoing');
243
- // Only start the output buffering if we care, and if it's NOT an XMLRPC REQUEST & NOT a tinyMCE JS file & NOT in the admin section
244
- if (($log_outgoing == 'true' || $log_outgoing === false) && (!defined('XMLRPC_REQUEST') || !XMLRPC_REQUEST) && !is_admin() && stripos($_SERVER['REQUEST_URI'], 'wp-includes/js/tinymce') === false) {
245
- ob_start(array('wpGoogleAnalytics', 'get_links'));
246
- }
247
  }
248
 
249
- /**
250
- * Grab all links on the page. If the code hasn't been inserted, we want to
251
- * insert it just before the </body> tag
252
- *
253
- * @param string $b - buffer contents
254
- * @return string - modified buffer contents
255
- */
256
- function get_links($b) {
257
- $b = preg_replace_callback("/
258
- <\s*a # anchor tag
259
- (?:\s[^>]*)? # other attibutes that we don't need
260
- \s*href\s*=\s* # href (required)
261
- (?:
262
- \"([^\"]*)\" # double quoted link
263
- |
264
- '([^']*)' # single quoted link
265
- |
266
- ([^'\"\s]*) # unquoted link
267
- )
268
- (?:\s[^>]*)? # other attibutes that we don't need
269
- \s*> #end of anchor tag
270
- /isUx", array('wpGoogleAnalytics', 'handle_link'), $b);
271
- return $b;
272
- }
273
-
274
- /**
275
- * If a link is outgoing, add an onclick that runs some Google JS with a
276
- * generated URL
277
- *
278
- * @param array $m - A match from the preg_replace_callback in self::get_links
279
- * @return string - modified andchor tag
280
- */
281
- function handle_link($m) {
282
- $code = wpGoogleAnalytics::get_options('code');
283
- //get our site url...used to see if the link is outgoing. We can't use the wordpress setting, because wordpress might not be running at the document root.
284
- $site_url = ( is_ssl() ? 'https://':'http://').$_SERVER['HTTP_HOST'];
285
- $link = array_pop($m);
286
- //If the link is outgoing, we modify $m[0] (the anchor tag)
287
- if (preg_match("/^https?:\/\//i", $link) && (strpos(strtolower($link), strtolower($site_url)) !== 0 )) {
288
- //get our custom link
289
- $track['data'] = $link;
290
- $track['code'] = 'outgoing';
291
- $track['url'] = wpGoogleAnalytics::get_url($track);
292
-
293
- // Check which version of the code the user is using, and user proper function
294
- $function = (strpos($code, 'ga.js') !== false)? 'pageTracker._trackPageview': 'urchinTracker';
295
- $onclick = "{$function}('{$track['url']}');";
296
-
297
- //If there is already an onclick, add to the beginning of it (adding to the end will not work, because too many people leave off the ; from the last statement)
298
- if (preg_match("/onclick\s*=\s*(['\"])/iUx",$m[0],$match)) {
299
- //If the onclick uses single quotes, we use double...and vice versa
300
- if ($match[1] == "'" ) {
301
- $onclick = str_replace("'", '"', $onclick);
302
- }
303
- $m[0] = str_replace($match[0], $match[0].$onclick, $m[0]);
304
- } else {
305
- $m[0] = str_replace('>', " onclick=\"{$onclick}\">", $m[0]);
306
- }
307
- }
308
- //return the anchor tag (modified or not)
309
- return $m[0];
310
- }
311
-
312
- function updateOption($oldValue, $newValue) {
313
- /**
314
- * @var WP_Roles
315
- */
316
- global $wp_roles;
317
-
318
- //Add/remove wga_no_track capability for each role
319
- foreach ($wp_roles->roles as $role=>$role_info) {
320
- if (isset($newValue[$role]) && $newValue[$role] == 'true') {
321
- $wp_roles->add_cap($role, 'wga_no_track', true);
322
- } else {
323
- $wp_roles->add_cap($role, 'wga_no_track', false);
324
- }
325
- }
326
- }
327
-
328
- function activatePlugin() {
329
- // If the wga-id has not been generated, generate one and store it.
330
- $o = get_option('wga');
331
- if (!isset($o['user_agreed_to_send_system_information'])) {
332
- $o['user_agreed_to_send_system_information'] = 'true';
333
- update_option('wga', $o);
334
- }
335
- }
336
  }
337
 
338
- /**
339
- * Add the necessary hooks
340
- */
341
- add_action('admin_menu', array('wpGoogleAnalytics','admin_menu'));
342
- add_action('get_footer', array('wpGoogleAnalytics', 'insert_code'));
343
- add_action('init', array('wpGoogleAnalytics', 'start_ob'));
344
- add_action('update_option_wga-roles', array('wpGoogleAnalytics', 'updateOption'), null, 2);
345
- add_action('activate_wp-google-analytics/wp-google-analytics.php', array('wpGoogleAnalytics', 'activatePlugin'));
346
- ?>
3
  * Plugin Name: WP Google Analytics
4
  * Plugin URI: http://bluedogwebservices.com/wordpress-plugin/wp-google-analytics/
5
  * Description: Lets you use <a href="http://analytics.google.com">Google Analytics</a> to track your WordPress site statistics
6
+ * Version: 1.3.0
7
  * Author: Aaron D. Campbell
8
  * Author URI: http://ran.ge/
9
+ * License: GPLv2 or later
10
+ * Text Domain: wp-google-analytics
11
  */
12
 
13
+ define('WGA_VERSION', '1.3.0');
14
 
15
  /* Copyright 2006 Aaron D. Campbell (email : wp_plugins@xavisys.com)
16
 
29
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30
  */
31
 
 
 
 
 
32
  /**
33
  * wpGoogleAnalytics is the class that handles ALL of the plugin functionality.
34
  * It helps us avoid name collisions
36
  */
37
  class wpGoogleAnalytics {
38
 
39
+ /**
40
+ * @var wpGoogleAnalytics - Static property to hold our singleton instance
41
+ */
42
+ static $instance = false;
43
+
44
+ static $page_slug = 'wp-google-analytics';
45
+
46
+ /**
47
+ * This is our constructor, which is private to force the use of get_instance()
48
+ * @return void
49
+ */
50
+ private function __construct() {
51
+ add_filter( 'init', array( $this, 'init_locale' ) );
52
+ add_action( 'admin_init', array( $this, 'admin_init' ) );
53
+ add_action( 'admin_menu', array( $this, 'admin_menu' ) );
54
+ add_action( 'get_footer', array( $this, 'insert_code' ) );
55
+ add_action( 'wp_enqueue_scripts', array( $this, 'track_outgoing' ) );
56
+ }
57
+
58
+ /**
59
+ * Function to instantiate our class and make it a singleton
60
+ */
61
+ public static function get_instance() {
62
+ if ( !self::$instance )
63
+ self::$instance = new self;
64
+
65
+ return self::$instance;
66
+ }
67
+
68
+ public function init_locale() {
69
+ load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
70
+ }
71
+
72
  /**
73
  * This adds the options page for this plugin to the Options page
74
  */
75
+ public function admin_menu() {
76
+ add_options_page(__('Google Analytics', 'wp-google-analytics'), __('Google Analytics', 'wp-google-analytics'), 'manage_options', self::$page_slug, array( $this, 'settings_view' ) );
77
  }
78
 
79
  /**
80
+ * Register our settings
81
+ */
82
+ public function admin_init() {
83
+ register_setting( 'wga', 'wga', array( $this, 'sanitize_general_options' ) );
84
+
85
+ add_settings_section( 'wga_general', false, '__return_false', 'wga' );
86
+ add_settings_field( 'code', __( 'Google Analytics tracking ID:', 'wp-google-analytics' ), array( $this, 'field_code' ), 'wga', 'wga_general' );
87
+ add_settings_field( 'additional_items', __( 'Additional items to log:', 'wp-google-analytics' ), array( $this, 'field_additional_items' ), 'wga', 'wga_general' );
88
+ add_settings_field( 'do_not_track', __( 'Visits to ignore:', 'wp-google-analytics' ), array( $this, 'field_do_not_track' ), 'wga', 'wga_general' );
89
+ add_settings_field( 'custom_vars', __( 'Custom variables:', 'wp-google-analytics' ), array( $this, 'field_custom_variables' ), 'wga', 'wga_general' );
90
+ }
91
+
92
+ /**
93
+ * Where the user adds their Google Analytics code
94
  */
95
+ public function field_code() {
96
+ echo '<input name="wga[code]" id="wga-code" type="text" value="' . esc_attr( $this->_get_options( 'code' ) ) . '" />';
97
+ echo '<p class="description">' . __( 'Paste your Google Analytics tracking ID (e.g. "UA-XXXXXX-X") into the field.', 'wp-google-analytics' ) . '</p>';
98
+ }
99
+
100
+ /**
101
+ * Option to log additional items
102
+ */
103
+ public function field_additional_items() {
104
+ $addtl_items = array(
105
+ 'log_404s' => __( 'Log 404 errors as events', 'wp-google-analytics' ),
106
+ '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/' ),
107
+ 'log_outgoing' => __( 'Log outgoing links as events', 'wp-google-analytics' ),
108
+ );
109
+ foreach( $addtl_items as $id => $label ) {
110
+ echo '<label for="wga_' . $id . '">';
111
+ echo '<input id="wga_' . $id . '" type="checkbox" name="wga[' . $id . ']" value="true" ' . checked( 'true', $this->_get_options( $id ), false ) . ' />';
112
+ echo '&nbsp;&nbsp;' . $label;
113
+ echo '</label><br />';
114
+ }
115
+ }
116
+
117
+ /**
118
+ * Define custom variables to be included in your tracking code
119
+ */
120
+ public function field_custom_variables() {
121
+ $custom_vars = $this->_get_options( 'custom_vars' );
122
+
123
+ $scope_options = array(
124
+ 0 => __( 'Default', 'wp-google-analytics' ),
125
+ 1 => __( 'Visitor', 'wp-google-analytics' ),
126
+ 2 => __( 'Session', 'wp-google-analytics' ),
127
+ 3 => __( 'Page', 'wp-google-analytics' ),
128
+ );
129
+ for ( $i = 1; $i <= 5; $i++ ) {
130
+ $name = ( isset( $custom_vars[$i]['name'] ) ) ? $custom_vars[$i]['name'] : '';
131
+ $value = ( isset( $custom_vars[$i]['value'] ) ) ? $custom_vars[$i]['value'] : '';
132
+ $scope = ( isset( $custom_vars[$i]['scope'] ) ) ? $custom_vars[$i]['scope'] : 0;
133
+ echo '<label for="wga_custom_var_' . $i . '_name"><strong>' . $i . ')</strong>&nbsp;' . __( 'Name', 'wp-google-analytics' ) . '&nbsp;';
134
+ echo '<input id="wga_custom_var_' . $i . '" type="text" name="wga[custom_vars][' . $i . '][name]" value="' . esc_attr( $name ) . '" />';
135
+ echo '</label>&nbsp;&nbsp;';
136
+ echo '<label for="wga_custom_var_' . $i . '_value">' . __( 'Value', 'wp-google-analytics' ) . '&nbsp;';
137
+ echo '<input id="wga_custom_var_' . $i . '" type="text" name="wga[custom_vars][' . $i . '][value]" value="' . esc_attr( $value ) . '" />';
138
+ echo '</label>&nbsp;&nbsp;';
139
+ echo '<label for="wga_custom_var_' . $i . '_scope">' . __( 'Scope', 'wp-google-analytics' ) . '&nbsp;';
140
+ echo '<select id="wga_custom_var_' . $i . '_scope" name="wga[custom_vars][' . $i . '][scope]">';
141
+ foreach( $scope_options as $key => $label ) {
142
+ echo '<option value="' . $key . '" ' . selected( $scope, $key, false ) . '>';
143
+ echo $label . '</option>';
144
+ }
145
+ echo '</select>';
146
+ echo '</label><br />';
147
+ }
148
+ }
149
+
150
+ public function field_do_not_track() {
151
+ $do_not_track = array(
152
+ 'ignore_admin_area' => __( 'Do not log anything in the admin area', 'wp-google-analytics' ),
153
+ );
154
  global $wp_roles;
155
+ foreach( $wp_roles->roles as $role => $role_info ) {
156
+ $do_not_track['ignore_role_' . $role] = sprintf( __( 'Do not log %s when logged in', 'wp-google-analytics' ), rtrim( $role_info['name'], 's' ) );
157
+ }
158
+ foreach( $do_not_track as $id => $label ) {
159
+ echo '<label for="wga_' . $id . '">';
160
+ echo '<input id="wga_' . $id . '" type="checkbox" name="wga[' . $id . ']" value="true" ' . checked( 'true', $this->_get_options( $id ), false ) . ' />';
161
+ echo '&nbsp;&nbsp;' . $label;
162
+ echo '</label><br />';
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Sanitize all of the options associated with the plugin
168
+ */
169
+ public function sanitize_general_options( $in ) {
170
+
171
+ $out = array();
172
 
173
+ // The actual tracking ID
174
+ if ( preg_match( '#UA-[\d-]+#', $in['code'], $matches ) )
175
+ $out['code'] = $matches[0];
176
+ else
177
+ $out['code'] = '';
178
+
179
+ $checkbox_items = array(
180
+ // Additional items you can track
181
+ 'log_404s',
182
+ 'log_searches',
183
+ 'log_outgoing',
184
+ // Things to ignore
185
+ 'ignore_admin_area',
186
+ );
187
+ global $wp_roles;
188
+ foreach( $wp_roles->roles as $role => $role_info ) {
189
+ $checkbox_items[] = 'ignore_role_' . $role;
190
  }
191
+ foreach( $checkbox_items as $checkbox_item ) {
192
+ if ( isset( $in[$checkbox_item] ) && 'true' == $in[$checkbox_item] )
193
+ $out[$checkbox_item] = 'true';
194
+ else
195
+ $out[$checkbox_item] = 'false';
196
+ }
197
+
198
+ // Custom variables
199
+ for( $i = 1; $i <= 5; $i++ ) {
200
+ foreach( array( 'name', 'value', 'scope' ) as $key ) {
201
+ if ( isset( $in['custom_vars'][$i][$key] ) )
202
+ $out['custom_vars'][$i][$key] = sanitize_text_field( $in['custom_vars'][$i][$key] );
203
+ else
204
+ $out['custom_vars'][$i][$key] = '';
205
+ }
206
  }
207
+
208
+ return $out;
209
+ }
210
+
211
+ /**
212
+ * This is used to display the options page for this plugin
213
+ */
214
+ public function settings_view() {
215
  ?>
216
  <div class="wrap">
217
+ <h2><?php _e('Google Analytics Options', 'wp-google-analytics') ?></h2>
218
  <form action="options.php" method="post" id="wp_google_analytics">
219
+ <?php
220
+ settings_fields( 'wga' );
221
+ do_settings_sections( 'wga' );
222
+ submit_button( __( 'Update Options', 'wp-google-analytics' ) );
223
+ ?>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
  </form>
225
  </div>
226
  <?php
232
  * @param array $track - Must have ['data'] and ['code']
233
  * @return string - Tracking URL
234
  */
235
+ private function _get_url($track) {
236
  $site_url = ( is_ssl() ? 'https://':'http://' ).$_SERVER['HTTP_HOST'];
237
  foreach ($track as $k=>$value) {
238
  if (strpos(strtolower($value), strtolower($site_url)) === 0) {
255
  return str_replace("'", "\'", "/{$track['code']}/{$track['data']}{$char}referer=" . urlencode( isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : '' ) );
256
  }
257
 
258
+ /**
259
+ * Maybe output or return, depending on the context
260
+ */
261
+ private function _output_or_return( $val, $maybe ) {
262
+ if ( $maybe )
263
+ echo $val . "\r\n";
264
+ else
265
+ return $val;
266
+ }
267
+
268
  /**
269
  * This injects the Google Analytics code into the footer of the page.
270
  *
271
  * @param bool[optional] $output - defaults to true, false returns but does NOT echo the code
272
  */
273
+ public function insert_code( $output = true ) {
274
  //If $output is not a boolean false, set it to true (default)
275
  $output = ($output !== false);
276
 
277
+ $tracking_id = $this->_get_options( 'code' );
278
+ if ( empty( $tracking_id ) )
279
+ return $this->_output_or_return( '<!-- Your Google Analytics Plugin is missing the tracking ID -->', $output );
280
+
281
  //get our plugin options
282
+ $wga = $this->_get_options();
283
  //If the user's role has wga_no_track set to true, return without inserting code
284
+ if ( is_user_logged_in() ) {
285
+ $current_user = wp_get_current_user();
286
+ $role = array_shift( $current_user->roles );
287
+ if ( 'true' == $this->_get_options( 'ignore_role_' . $role ) )
288
+ return $this->_output_or_return( "<!-- Google Analytics Plugin is set to ignore your user role -->", $output );
 
289
  }
 
 
 
 
 
 
290
 
291
+ //If $admin is true (we're in the admin_area), and we've been told to ignore_admin_area, return without inserting code
292
+ if (is_admin() && (!isset($wga['ignore_admin_area']) || $wga['ignore_admin_area'] != 'false'))
293
+ return $this->_output_or_return( "<!-- Your Google Analytics Plugin is set to ignore Admin area -->", $output );
 
 
 
 
 
 
 
 
 
 
 
 
 
294
 
295
+ $custom_vars = array(
296
+ "_gaq.push(['_setAccount', '{$tracking_id}']);",
297
+ );
 
298
 
299
+ $track = array();
300
+ if (is_404() && (!isset($wga['log_404s']) || $wga['log_404s'] != 'false')) {
301
+ // This is a 404 and we are supposed to track them
302
+ $custom_vars[] = "_gaq.push( [ '_trackEvent', '404', document.location.href, document.referrer ] );";
303
+ } elseif (is_search() && (!isset($wga['log_searches']) || $wga['log_searches'] != 'false')) {
304
+ //Set track for searches, if it's a search, and we are supposed to
305
+ $track['data'] = $_REQUEST['s'];
306
+ $track['code'] = "search";
307
+ }
308
 
309
+ if ( ! empty( $track ) ) {
310
+ $track['url'] = $this->_get_url( $track );
311
+ //adjust the code that we output, account for both types of tracking
312
+ $track['url'] = esc_js( str_replace( '&', '&amp;', $track['url'] ) );
313
+ $custom_vars[] = "_gaq.push(['_trackPageview','{$track['url']}']);";
 
 
 
 
 
314
  } else {
315
+ $custom_vars[] = "_gaq.push(['_trackPageview']);";
 
 
 
 
 
316
  }
317
+
318
+ // Add custom variables specified by the user
319
+ foreach( $this->_get_options( 'custom_vars', array() ) as $i => $custom_var ) {
320
+ if ( empty( $custom_var['name'] ) || empty( $custom_var['value'] ) )
321
+ continue;
322
+ $atts = array(
323
+ "'_setCustomVar'",
324
+ intval( $i ),
325
+ "'" . esc_js( $custom_var['name'] ) . "'",
326
+ "'" . esc_js( $custom_var['value'] ) . "'",
327
+ );
328
+ if ( $custom_var['scope'] )
329
+ $atts[] = intval( $custom_var['scope'] );
330
+ $custom_vars[] = "_gaq.push([" . implode( ', ', $atts ) . "]);";
331
+ }
332
+
333
+ $async_code = "<script type='text/javascript'>
334
+ var _gaq = _gaq || [];
335
+ %custom_vars%
336
+
337
+ (function() {
338
+ var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
339
+ ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
340
+ var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
341
+ })();
342
+ </script>";
343
+ $custom_vars_string = implode( "\r\n", $custom_vars );
344
+ $async_code = str_replace( '%custom_vars%', $custom_vars_string, $async_code );
345
+
346
+ return $this->_output_or_return( $async_code, $output );
347
+
348
  }
349
 
350
  /**
353
  * @param string[optional] $option - Name of options you want. Do not use if you want ALL options
354
  * @return array of options, or option value
355
  */
356
+ private function _get_options( $option = null, $default = false ) {
357
+
358
  $o = get_option('wga');
359
+
360
  if (isset($option)) {
361
+
362
  if (isset($o[$option])) {
363
+ if ( 'code' == $option ) {
364
+ if ( preg_match( '#UA-[\d-]+#', $o[$option], $matches ) )
365
+ return $matches[0];
366
+ else
367
+ return '';
368
+ } else
369
+ return $o[$option];
370
  } else {
371
+ if ( 'ignore_role_' == substr( $option, 0, 12 ) ) {
372
+ global $wp_roles;
373
+ // Backwards compat for when the tracking information was stored as a cap
374
+ $maybe_role = str_replace( 'ignore_role_', '', $option );
375
+ if ( isset( $wp_roles->roles[$maybe_role] ) ) {
376
+ if ( isset( $wp_roles->roles[$maybe_role]['capabilities']['wga_no_track'] ) && $wp_roles->roles[$maybe_role]['capabilities']['wga_no_track'] )
377
+ return 'true';
378
+ }
379
+ return false;
380
+ }
381
+ return $default;
382
  }
383
  } else {
384
  return $o;
386
  }
387
 
388
  /**
389
+ * If we track outgoing links, this will enqueue our javascript file
 
 
390
  */
391
+ public function track_outgoing() {
392
+ $wga = $this->_get_options();
393
+ if ( 'true' == $wga['log_outgoing'] && (!defined('XMLRPC_REQUEST') || !XMLRPC_REQUEST) && ( ! is_admin() || $wga['ignore_admin_area'] == 'false') )
394
+ wp_enqueue_script( 'wp-google-analytics', plugin_dir_url( __FILE__ ) . 'wp-google-analytics.js', array( 'jquery' ), '0.0.3' );
 
 
395
  }
396
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
397
  }
398
 
399
+ global $wp_google_analytics;
400
+ $wp_google_analytics = wpGoogleAnalytics::get_instance();