WP Google Analytics - Version 1.0.0

Version Description

Download this release

Release Info

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

Version 1.0.0

Files changed (2) hide show
  1. readme.txt +40 -0
  2. wp-google-analytics.php +350 -0
readme.txt ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ === WP Google Analytics ===
2
+ Contributors: aaroncampbell
3
+ Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=paypal%40xavisys%2ecom&item_name=Google%20Analytics%20Plugin&no_shipping=0&no_note=1&tax=0&currency_code=USD&lc=US&bn=PP%2dDonationsBF&charset=UTF%2d8
4
+ Tags: analytics, google, google analytics
5
+ Requires at least: 1.5
6
+ Tested up to: 2.5.1
7
+ Stable tag: 1.0.0
8
+
9
+ Lets you use <a href="http://analytics.google.com">Google Analytics</a> to track your WordPress site statistics
10
+
11
+ == Description ==
12
+
13
+ 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
+
24
+ 1. Upload the `wp-google-analytics.php` file to the `/wp-content/plugins/` directory
25
+ 1. Activate the plugin through the 'Plugins' menu in WordPress
26
+
27
+ == Frequently Asked Questions ==
28
+
29
+ = Where do I put my Google Analytics Code? =
30
+
31
+ WP Google Analytics has a config page under the settings tab in the admin area
32
+ of your site. You can paste your tracking code from Google into the textarea on
33
+ this page.
34
+
35
+ = Can't I just paste the Google Analytics code into my template file? =
36
+
37
+ Absolutely, however in order to get a better idea of what is going on with your
38
+ site, it is often nice to have your own activities ignored, track 404s, searches
39
+ and even where users go when they leave your site. WP Google Analytics lets you
40
+ easily do all these things.
wp-google-analytics.php ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Plugin Name: WP Google Analytics
4
+ * Plugin URI: http://xavisys.com/wordpress-google-analytics-plugin/
5
+ * Description: Lets you use <a href="http://analytics.google.com">Google Analytics</a> to track your WordPress site statistics
6
+ * Version: 1.0.0
7
+ * Author: Aaron D. Campbell
8
+ * Author URI: http://xavisys.com/
9
+ */
10
+
11
+ /**
12
+ * Changelog:
13
+ * 04/17/2008: 1.0.0
14
+ * - Added to wordpress.org repository
15
+ *
16
+ * 07/03/2007: 0.2
17
+ * - Fixed problem with themes that do not call wp_footer(). If you are reading this and you are a theme developer, USE THE HOOKS! That's what they're there for!
18
+ * - Updated how the admin section is handled
19
+ *
20
+ * 02/21/2007: 0.1
21
+ * - Original Version
22
+ */
23
+
24
+ /* Copyright 2006 Aaron D. Campbell (email : wp_plugins@xavisys.com)
25
+
26
+ This program is free software; you can redistribute it and/or modify
27
+ it under the terms of the GNU General Public License as published by
28
+ the Free Software Foundation; either version 2 of the License, or
29
+ (at your option) any later version.
30
+
31
+ This program is distributed in the hope that it will be useful,
32
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
33
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34
+ GNU General Public License for more details.
35
+
36
+ You should have received a copy of the GNU General Public License
37
+ along with this program; if not, write to the Free Software
38
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
39
+ */
40
+
41
+ //If this is set to true, extra info will be dumped to the browser.
42
+ //ONLY do this if you really need it
43
+ define('WGA_DEBUG', false);
44
+
45
+ /**
46
+ * wpGoogleAnalytics is the class that handles ALL of the plugin functionality.
47
+ * It helps us avoid name collisions
48
+ * http://codex.wordpress.org/Writing_a_Plugin#Avoiding_Function_Name_Collisions
49
+ */
50
+ class wpGoogleAnalytics {
51
+
52
+ /**
53
+ * This adds the options page for this plugin to the Options page
54
+ */
55
+ function admin_menu() {
56
+ add_options_page(__('Google Analytics'), __('Google Analytics'), 'manage_options', str_replace("\\", "/", __FILE__), array('wpGoogleAnalytics', 'options'));
57
+ }
58
+
59
+ /**
60
+ * This is used to display the options page for this plugin
61
+ */
62
+ function options() {
63
+ /**
64
+ * @var WP_Roles
65
+ */
66
+ global $wp_roles;
67
+
68
+ //Deal with the data when submitted
69
+ if (isset($_POST['wga_submit'])) {
70
+ //Google Analytics Code
71
+ $_POST['wga']['code'] = stripslashes($_POST['wga']['code']);
72
+ //Special logging of 404s
73
+ $_POST['wga']['log_404s'] = (!isset($_POST['wga']['log_404s']) || strtolower($_POST['wga']['log_404s']) != 'true')? 'false':'true';
74
+ //Special logging of searches
75
+ $_POST['wga']['log_searches'] = (!isset($_POST['wga']['log_searches']) || strtolower($_POST['wga']['log_searches']) != 'true')? 'false':'true';
76
+ //Special logging of outgoing link
77
+ $_POST['wga']['log_outgoing'] = (!isset($_POST['wga']['log_outgoing']) || strtolower($_POST['wga']['log_outgoing']) != 'true')? 'false':'true';
78
+ //Ignore admin area
79
+ $_POST['wga']['ignore_admin_area'] = (!isset($_POST['wga']['ignore_admin_area']) || strtolower($_POST['wga']['ignore_admin_area']) != 'true')? 'false':'true';
80
+ //Add/remove wga_no_track capability for each role
81
+ foreach ($wp_roles->roles as $role=>$role_info) {
82
+ if (isset($_POST['wga']['role'][$role]) && $_POST['wga']['role'][$role] == 'true') {
83
+ $wp_roles->add_cap($role, 'wga_no_track', true);
84
+ } else {
85
+ $wp_roles->add_cap($role, 'wga_no_track', false);
86
+ }
87
+ }
88
+ //We don't need to store this in our setting
89
+ unset($_POST['wga']['role']);
90
+ //update our option
91
+ update_option('wga', $_POST['wga']);
92
+ echo '<div class="updated fade"><p>'.__('Options Updated.').'</p></div>';
93
+ }
94
+
95
+ //Get our options
96
+ $wga = wpGoogleAnalytics::get_options();
97
+ //Echo debug info if needed
98
+ if (WGA_DEBUG) {
99
+ echo '<pre>',var_dump($wga),'</pre>';
100
+ }
101
+ //We will fill $roles with checkboxes to ignore each role
102
+ $roles = '';
103
+ foreach ($wp_roles->roles as $role=>$role_info) {
104
+ $checked = (isset($role_info['capabilities']['wga_no_track']) && $role_info['capabilities']['wga_no_track'])? ' checked="checked"':'';
105
+ $role_info['name'] .= (strtolower(substr($role_info['name'], -1)) != 's')? 's':'';
106
+ $roles .= " <label for='wga_role_{$role}'><input type='checkbox' name='wga[role][{$role}]' value='true' id='wga_role_{$role}'{$checked} /> ".__("Do not log {$role_info['name']} when logged in")."</label><br />";
107
+ }
108
+ ?>
109
+ <div class="wrap">
110
+ <h2><?php _e('Google Analytics Options') ?></h2>
111
+ <form action="" method="post" id="wp_google_analytics">
112
+ <fieldset class="options">
113
+ <legend><?php _e('Google Analytics Code'); ?></legend>
114
+ <label for="wga_code">
115
+ <?php _e('Paste your <a href="http://analytics.google.com">Google Analytics</a> code into the textarea:'); ?><br /><br />
116
+ <textarea name="wga[code]" id="wga_code" style="width:400px; height:150px;"><?php echo htmlentities($wga['code']); ?></textarea><br /><br />
117
+ </label>
118
+ <label for="wga_ignore_admin_area"><input type="checkbox" name="wga[ignore_admin_area]" value="true" id="wga_ignore_admin_area" <?php if ($wga['ignore_admin_area'] == 'true') { echo ' checked="checked"';} ?> /> <?php _e('Do not log anything in the admin area'); ?></label><br />
119
+ <label for="wga_log_404s"><input type="checkbox" name="wga[log_404s]" value="true" id="wga_log_404s" <?php if ($wga['log_404s'] == 'true') { echo ' checked="checked"';} ?> /> <?php _e('Log 404 errors as /404/{url}?referrer={referrer}'); ?></label><br />
120
+ <label for="wga_log_searches"><input type="checkbox" name="wga[log_searches]" value="true" id="wga_log_searches" <?php if ($wga['log_searches'] == 'true') { echo ' checked="checked"';} ?> /> <?php _e('Log searches as /search/{search}?referrer={referrer}'); ?></label><br />
121
+ <label for="wga_log_outgoing"><input type="checkbox" name="wga[log_outgoing]" value="true" id="wga_log_outgoing" <?php if ($wga['log_outgoing'] == 'true') { echo ' checked="checked"';} ?> /> <?php _e('Log outgoing links as /outgoing/{url}?referrer={referrer}'); ?></label><br />
122
+ <?php echo $roles; ?>
123
+ </fieldset>
124
+ <p class="submit">
125
+ <input type="submit" name="wga_submit" value="Update Options &raquo;" />
126
+ </p>
127
+ </form>
128
+ </div>
129
+ <?php
130
+ }
131
+
132
+ /**
133
+ * Used to generate a tracking URL
134
+ *
135
+ * @param array $track - Must have ['data'] and ['code']
136
+ * @return string - Tracking URL
137
+ */
138
+ function get_url($track) {
139
+ $site_url = (($_SERVER['HTTPS'] == 'on')? 'https://':'http://').$_SERVER['HTTP_HOST'];
140
+ foreach ($track as $k=>$value) {
141
+ if (strpos(strtolower($value), strtolower($site_url)) === 0) {
142
+ $track[$k] = substr($track[$k], strlen($site_url));
143
+ }
144
+ if ($k == 'data') {
145
+ $track[$k] = preg_replace("/^https?:\/\/|^\/+/i", "", $track[$k]);
146
+ }
147
+
148
+ //This way we don't lose search data.
149
+ if ($k == 'data' && $track['code'] == 'search') {
150
+ $track[$k] = urlencode($track[$k]);
151
+ } else {
152
+ $track[$k] = preg_replace("/[^a-z0-9\.\/\+\?=-]+/i", "_", $track[$k]);
153
+ }
154
+
155
+ $track[$k] = trim($track[$k], '_');
156
+ }
157
+ $char = (strpos($track['data'], '?') === false)? '?':'&';
158
+ return str_replace("'", "\'", "/{$track['code']}/{$track['data']}{$char}referer={$_SERVER['HTTP_REFERER']}");
159
+ }
160
+
161
+ /**
162
+ * This injects the Google Analytics code into the head of the page.
163
+ *
164
+ * @param bool[optional] $output - defaults to true, false returns but does NOT echo the code
165
+ */
166
+ function insert_code($output=true) {
167
+ //If $output is not a boolean false, set it to true (default)
168
+ $output = ($output !== false);
169
+ //This sets a static variable that says if the code has been inserted.
170
+ wpGoogleAnalytics::code_inserted_static(true);
171
+ //get our plugin options
172
+ $wga = wpGoogleAnalytics::get_options();
173
+ //If the user's role has wga_no_track set to true, return without inserting code
174
+ if (current_user_can('wga_no_track')) {
175
+ $ret = "<!-- Google Analytics Plugin is set to ignore your user role -->\r\n";
176
+ if ($output) {
177
+ echo $ret;
178
+ }
179
+ return $ret;
180
+ }
181
+ //If the Google Analytics code has been set
182
+ if ($wga['code'] !== false) {
183
+ //Echo debug info if needed
184
+ if (WGA_DEBUG) {
185
+ echo '<pre>',var_dump($wga),'</pre>';
186
+ }
187
+
188
+ //If $admin is true (we're in the admin_area), and we've been told to ignore_admin_area, return without inserting code
189
+ if (is_admin() && (!isset($wga['ignore_admin_area']) || $wga['ignore_admin_area'] != 'false')) {
190
+ $ret = "<!-- Your Google Analytics Plugin is set to ignore Admin area -->\r\n";
191
+ if ($output) {
192
+ echo $ret;
193
+ }
194
+ return $ret;
195
+ } elseif (is_404() && (!isset($wga['log_404s']) || $wga['log_404s'] != 'false')) {
196
+ //Set track for 404s, if it's a 404, and we are supposed to
197
+ $track['data'] = $_SERVER['REQUEST_URI'];
198
+ $track['code'] = '404';
199
+ } elseif (is_search() && (!isset($wga['log_searches']) || $wga['log_searches'] != 'false')) {
200
+ //Set track for searches, if it's a search, and we are supposed to
201
+ $track['data'] = $_REQUEST['s'];
202
+ $track['code'] = "search";
203
+ }
204
+
205
+ //If we need to generate a special tracking URL
206
+ if (isset($track)) {
207
+ //get the tracking URL
208
+ $track['url'] = wpGoogleAnalytics::get_url($track);
209
+ //adjust the code that we output
210
+ $wga['code'] = str_replace("urchinTracker()","urchinTracker('{$track['url']}')", $wga['code']);
211
+ //Echo debug info if needed
212
+ if (WGA_DEBUG) {
213
+ echo '<pre>',var_dump($track, $site_url),'</pre>';
214
+ }
215
+ }
216
+ //output the Google Analytics code
217
+ if ($output) {
218
+ echo $wga['code'];
219
+ }
220
+ return $wga['code'];
221
+ } else {
222
+ //If the Google Analytics code has not been set in admin area, return without inserting code
223
+ $ret = "<!-- You need to set up the Google Analytics Plugin -->\r\n";
224
+ if ($output) {
225
+ echo $ret;
226
+ }
227
+ return $ret;
228
+ }
229
+ }
230
+
231
+ /**
232
+ * Used to get one or all of our plugin options
233
+ *
234
+ * @param string[optional] $option - Name of options you want. Do not use if you want ALL options
235
+ * @return array of options, or option value
236
+ */
237
+ function get_options($option = null) {
238
+ $o = get_option('wga');
239
+ if (isset($option)) {
240
+ if (isset($o[$option])) {
241
+ return $o[$option];
242
+ } else {
243
+ return false;
244
+ }
245
+ } else {
246
+ return $o;
247
+ }
248
+ }
249
+
250
+ /**
251
+ * Start our output buffering with a callback, to grab all links
252
+ *
253
+ * @todo If there is a good way to tell if this is a feed, add a seperate option for tracking outgoings on feeds
254
+ */
255
+ function start_ob() {
256
+ $log_outgoing = wpGoogleAnalytics::get_options('log_outgoing');
257
+ //Only start the output buffering if we care, and if it's NOT an XMLRPC REQUEST
258
+ if (($log_outgoing == 'true' || $log_outgoing === false) && (!defined('XMLRPC_REQUEST') || !XMLRPC_REQUEST)) {
259
+ ob_start(array('wpGoogleAnalytics', 'get_links'));
260
+ }
261
+ }
262
+
263
+ /**
264
+ * Grab all links on the page. If the code hasn't been inserted, we want to
265
+ * insert it just before the </body> tag
266
+ *
267
+ * @param string $b - buffer contents
268
+ * @return string - modified buffer contents
269
+ */
270
+ function get_links($b) {
271
+ $b = preg_replace_callback("/
272
+ <\s*a # anchor tag
273
+ (?:\s[^>]*)? # other attibutes that we don't need
274
+ \s*href\s*=\s* # href (required)
275
+ (?:
276
+ \"([^\"]*)\" # double quoted link
277
+ |
278
+ '([^']*)' # single quoted link
279
+ |
280
+ ([^'\"\s]*) # unquoted link
281
+ )
282
+ (?:\s[^>]*)? # other attibutes that we don't need
283
+ \s*> #end of anchor tag
284
+ /isUx", array('wpGoogleAnalytics', 'handle_link'), $b);
285
+ //If the code hasn't been inserted, take drastic measures and add it here
286
+ if (!wpGoogleAnalytics::code_inserted_static()) {
287
+ $b = str_replace('</body>', wpGoogleAnalytics::insert_code(false).'</body>', $b);
288
+ }
289
+ return $b;
290
+ }
291
+
292
+ /**
293
+ * If a link is outgoing, add an onclick that runs urchinTracker with a
294
+ * generated URL
295
+ *
296
+ * @param array $m - A match from the preg_replace_callback in self::get_links
297
+ * @return string - modified andchor tag
298
+ */
299
+ function handle_link($m) {
300
+ //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.
301
+ $site_url = (($_SERVER['HTTPS'] == 'on')? 'https://':'http://').$_SERVER['HTTP_HOST'];
302
+ $link = array_pop($m);
303
+ //If the link is outgoing, we modify $m[0] (the anchor tag)
304
+ if (preg_match("/^https?:\/\//i", $link) && (strpos(strtolower($link), strtolower($site_url)) !== 0 )) {
305
+ //get our custom link
306
+ $track['data'] = $link;
307
+ $track['code'] = 'outgoing';
308
+ $track['url'] = wpGoogleAnalytics::get_url($track);
309
+
310
+ //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)
311
+ if (preg_match("/onclick\s*=\s*(['\"])/iUx",$m[0],$match)) {
312
+ //If the onclick uses single quotes, we use double...and vice versa
313
+ if ($match[1] == "'" ) {
314
+ $onclick = "urchinTracker(\"{$track['url']}\");";
315
+ } else {
316
+ $onclick = "urchinTracker('{$track['url']}');";
317
+ }
318
+ $m[0] = str_replace($match[0], $match[0].$onclick, $m[0]);
319
+ } else {
320
+ $m[0] = str_replace('>', " onclick=\"{$onclick}\">", $m[0]);
321
+ }
322
+ }
323
+ //return the anchor tag (modified or not)
324
+ return $m[0];
325
+ }
326
+
327
+ /**
328
+ * This is a lame PHP4 hack since PHP4 doesn't support static class variables.
329
+ * One of these days I'm just going to say "screw people that won't upgrade"
330
+ * and do ONLY PHP5
331
+ *
332
+ * @param mixed $set[optional] - What to set the static var to
333
+ * @return mixed - value of static var
334
+ */
335
+ function code_inserted_static($set = null) {
336
+ static $static = false;
337
+ if (!is_null($set)) {
338
+ $static = $set;
339
+ }
340
+ return $static;
341
+ }
342
+ }
343
+
344
+ /**
345
+ * Add the necessary hooks
346
+ */
347
+ add_action('admin_menu', array('wpGoogleAnalytics','admin_menu'));
348
+ add_action('wp_footer', array('wpGoogleAnalytics', 'insert_code'));
349
+ add_action('init', array('wpGoogleAnalytics', 'start_ob'));
350
+ ?>