Stripping CVS keywords
[project/google_analytics.git] / googleanalytics.module
1 <?php
2
3 /*
4 * @file
5 * Drupal Module: GoogleAnalytics
6 * Adds the required Javascript to the bottom of all your Drupal pages
7 * to allow tracking by the Google Analytics statistics package.
8 *
9 * @author: Alexander Hass <http://drupal.org/user/85918>
10 */
11
12 define('GA_TRACKFILES_EXTENSIONS', '7z|aac|arc|arj|asf|asx|avi|bin|csv|doc|exe|flv|gif|gz|gzip|hqx|jar|jpe?g|js|mp(2|3|4|e?g)|mov(ie)?|msi|msp|pdf|phps|png|ppt|qtm?|ra(m|r)?|sea|sit|tar|tgz|torrent|txt|wav|wma|wmv|wpd|xls|xml|z|zip');
13
14 /**
15 * Implements hook_help().
16 */
17 function googleanalytics_help($path, $arg) {
18 switch ($path) {
19 case 'admin/config/system/googleanalytics':
20 return t('<a href="@ga_url">Google Analytics</a> is a free (registration required) website traffic and marketing effectiveness service.', array('@ga_url' => 'http://www.google.com/analytics/'));
21 }
22 }
23
24 /**
25 * Implements hook_theme().
26 */
27 function googleanalytics_theme() {
28 return array(
29 'googleanalytics_admin_custom_var_table' => array(
30 'render element' => 'form',
31 ),
32 );
33 }
34
35 /**
36 * Implements hook_permission().
37 */
38 function googleanalytics_permission() {
39 return array(
40 'administer google analytics' => array(
41 'title' => t('Administer Google Analytics'),
42 'description' => t('Perform maintenance tasks for Google Analytics.'),
43 ),
44 'opt-in or out of tracking' => array(
45 'title' => t('Opt-in or out of tracking'),
46 'description' => t('Allow users to decide if tracking code will be added to pages or not.'),
47 ),
48 'use PHP for tracking visibility' => array(
49 'title' => t('Use PHP for tracking visibility'),
50 'description' => t('Enter PHP code in the field for tracking visibility settings. %warning', array('%warning' => t('Warning: Give to trusted roles only; this permission has security implications.'))),
51 ),
52 );
53 }
54
55 /**
56 * Implements hook_menu().
57 */
58 function googleanalytics_menu() {
59 $items['admin/config/system/googleanalytics'] = array(
60 'title' => 'Google Analytics',
61 'description' => 'Configure tracking behavior to get insights into your website traffic and marketing effectiveness.',
62 'page callback' => 'drupal_get_form',
63 'page arguments' => array('googleanalytics_admin_settings_form'),
64 'access arguments' => array('administer google analytics'),
65 'type' => MENU_NORMAL_ITEM,
66 'file' => 'googleanalytics.admin.inc',
67 );
68
69 return $items;
70 }
71
72 /**
73 * Implements hook_page_alter() to insert JavaScript to the appropriate scope/region of the page.
74 */
75 function googleanalytics_page_alter(&$page) {
76 global $user;
77
78 $id = variable_get('googleanalytics_account', '');
79
80 // Get page status code for visibility filtering.
81 $status = drupal_get_http_header('Status');
82 $trackable_status_codes = array(
83 '403 Forbidden',
84 '404 Not Found',
85 );
86
87 // 1. Check if the GA account number has a value.
88 // 2. Track page views based on visibility value.
89 // 3. Check if we should track the currently active user's role.
90 // 4. Ignore pages visibility filter for 404 or 403 status codes.
91 if (!empty($id) && (_googleanalytics_visibility_pages() || in_array($status, $trackable_status_codes)) && _googleanalytics_visibility_user($user)) {
92
93 // We allow different scopes. Default to 'header' but allow user to override if they really need to.
94 $scope = variable_get('googleanalytics_js_scope', 'header');
95
96 if (variable_get('googleanalytics_trackadsense', FALSE)) {
97 // Custom tracking. Prepend before all other JavaScript.
98 drupal_add_js('window.google_analytics_uacct = ' . drupal_json_encode($id) . ';', array('type' => 'inline', 'group' => JS_LIBRARY-1));
99 }
100
101 // Add link tracking.
102 $link_settings = array();
103 if ($track_outbound = variable_get('googleanalytics_trackoutbound', 1)) {
104 $link_settings['trackOutbound'] = $track_outbound;
105 }
106 if ($track_mailto = variable_get('googleanalytics_trackmailto', 1)) {
107 $link_settings['trackMailto'] = $track_mailto;
108 }
109 if (($track_download = variable_get('googleanalytics_trackfiles', 1)) && ($trackfiles_extensions = variable_get('googleanalytics_trackfiles_extensions', GA_TRACKFILES_EXTENSIONS))) {
110 $link_settings['trackDownload'] = $track_download;
111 $link_settings['trackDownloadExtensions'] = $trackfiles_extensions;
112 }
113 if ($track_outbound_as_pageview = variable_get('googleanalytics_trackoutboundaspageview', 0)) {
114 $link_settings['trackOutboundAsPageview'] = $track_outbound_as_pageview;
115 }
116 if ($track_domain_mode = variable_get('googleanalytics_domain_mode', 0)) {
117 $link_settings['trackDomainMode'] = $track_domain_mode;
118 }
119 if ($track_cross_domains = variable_get('googleanalytics_cross_domains', '')) {
120 $domains = preg_split('/(\r\n?|\n)/', $track_cross_domains);
121 $link_settings['trackCrossDomains'] = implode('|', $domains);
122 }
123
124 if (!empty($link_settings)) {
125 drupal_add_js(array('googleanalytics' => $link_settings), 'setting');
126 drupal_add_js(drupal_get_path('module', 'googleanalytics') . '/googleanalytics.js');
127 }
128
129 // Add User profile segmentation values.
130 $profile_fields = variable_get('googleanalytics_segmentation', array());
131 if (!empty($profile_fields)) {
132 // Invoke all modules having a hook_user_load() implemented.
133 // If the invoked modules extend the $user object, the additional
134 // data can be tracked.
135 module_invoke_all('user_load', array($user->uid => $user));
136
137 $fields = array();
138 foreach ($profile_fields as $field => $title) {
139 $fields[$field] = is_array($user->$field) ? implode(',', $user->$field) : $user->$field;
140 }
141
142 // Only show segmentation variable if there are specified fields.
143 $segmentation = '';
144 if (count($fields) > 0) {
145 $segmentation = '_gaq.push(["_setVar", ' . drupal_json_encode(implode(':', $fields)) . ']);';
146 }
147 }
148
149 // Site search tracking support.
150 $url_custom = '';
151 if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE) && arg(0) == 'search' && $keys = googleanalytics_search_get_keys()) {
152 $url_custom = drupal_json_encode(rawurldecode(url('search/' . arg(1), array('query' => array('search' => $keys)))));
153 }
154
155 // If this node is a translation of another node, pass the original
156 // node instead.
157 if (module_exists('translation') && variable_get('googleanalytics_translation_set', 0)) {
158 // Check we have a node object, it supports translation, and its
159 // translated node ID (tnid) doesn't match its own node ID.
160 $node = menu_get_object();
161 if ($node && translation_supported_type($node->type) && isset($node->tnid) && ($node->tnid != $node->nid)) {
162 $source_node = node_load($node->tnid);
163 $languages = language_list();
164 $url_custom = drupal_json_encode(url('node/' . $source_node->nid, array('language' => $languages[$source_node->language])));
165 }
166 }
167
168 // Track access denied (403) and file not found (404) pages.
169 if ($status == '403 Forbidden') {
170 // See http://www.google.com/support/analytics/bin/answer.py?answer=86927
171 $url_custom = '"/403.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
172 }
173 elseif ($status == '404 Not Found') {
174 $url_custom = '"/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
175 }
176
177 // Add any custom code snippets if specified.
178 $codesnippet_before = variable_get('googleanalytics_codesnippet_before', '');
179 $codesnippet_after = variable_get('googleanalytics_codesnippet_after', '');
180
181 // Add custom variables.
182 $googleanalytics_custom_vars = variable_get('googleanalytics_custom_var', array());
183 $custom_var = '';
184 for ($i = 1; $i < 6; $i++) {
185 $custom_var_name = !empty($googleanalytics_custom_vars['slots'][$i]['name']) ? $googleanalytics_custom_vars['slots'][$i]['name'] : '';
186 if (!empty($custom_var_name)) {
187 $custom_var_value = !empty($googleanalytics_custom_vars['slots'][$i]['value']) ? $googleanalytics_custom_vars['slots'][$i]['value'] : '';
188 $custom_var_scope = !empty($googleanalytics_custom_vars['slots'][$i]['scope']) ? $googleanalytics_custom_vars['slots'][$i]['scope'] : 3;
189
190 $node = menu_get_object();
191 $custom_var_value = token_replace($custom_var_value, array('node' => $node), array('clear' => TRUE));
192
193 // Suppress empty custom variables.
194 if (!is_numeric($custom_var_value) && empty($custom_var_value)) {
195 continue;
196 }
197
198 // The length of the string used for the 'name' and the length of the
199 // string used for the 'value' must not exceed 64 bytes after url encoding.
200 $name_length = drupal_strlen(rawurlencode($custom_var_name));
201 $tmp_value = rawurlencode($custom_var_value);
202 $value_length = drupal_strlen($tmp_value);
203 if ($name_length + $value_length > 64) {
204 // Trim value and remove fragments of url encoding.
205 $tmp_value = rtrim(substr($tmp_value, 0, 63 - $name_length), '%0..9A..F');
206 $custom_var_value = urldecode($tmp_value);
207 }
208
209 $custom_var_name = drupal_json_encode($custom_var_name);
210 $custom_var_value = drupal_json_encode($custom_var_value);
211 $custom_var .= "_gaq.push(['_setCustomVar', $i, $custom_var_name, $custom_var_value, $custom_var_scope]);";
212 }
213 }
214
215 // Build tracker code.
216 $script = 'var _gaq = _gaq || [];';
217 $script .= '_gaq.push(["_setAccount", ' . drupal_json_encode($id) . ']);';
218 if (variable_get('googleanalytics_tracker_anonymizeip', 0)) {
219 // FIXME: The Google API is currently broken and "_gat._anonymizeIp" is only
220 // a workaround until "_anonymizeIp" has been implemented/fixed.
221 $script .= '_gaq.push(["_gat._anonymizeIp"]);';
222 }
223
224 // Domain tracking type.
225 global $cookie_domain;
226 $domain_mode = variable_get('googleanalytics_domain_mode', 0);
227
228 // Per RFC 2109, cookie domains must contain at least one dot other than the
229 // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
230 if ($domain_mode == 1 && count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
231 $script .= '_gaq.push(["_setDomainName", ' . drupal_json_encode($cookie_domain) . ']);';
232 }
233 elseif ($domain_mode == 2) {
234 $script .= '_gaq.push(["_setDomainName", "none"]);';
235 $script .= '_gaq.push(["_setAllowLinker", true]);';
236 }
237
238 if (!empty($segmentation)) {
239 $script .= $segmentation;
240 }
241 if (!empty($codesnippet_before)) {
242 $script .= $codesnippet_before;
243 }
244 if (!empty($custom_var)) {
245 $script .= $custom_var;
246 }
247 if (empty($url_custom)) {
248 $script .= '_gaq.push(["_trackPageview"]);';
249 }
250 else {
251 $script .= '_gaq.push(["_trackPageview", ' . $url_custom . ']);';
252 }
253 if (!empty($codesnippet_after)) {
254 $script .= $codesnippet_after;
255 }
256
257 $script .= '(function() {';
258 $script .= 'var ga = document.createElement("script");';
259 $script .= 'ga.type = "text/javascript";';
260 $script .= 'ga.async = true;';
261
262 // Should a local cached copy of ga.js be used?
263 if (variable_get('googleanalytics_cache', 0) && $url = _googleanalytics_cache('http://www.google-analytics.com/ga.js')) {
264 // A dummy query-string is added to filenames, to gain control over
265 // browser-caching. The string changes on every update or full cache
266 // flush, forcing browsers to load a new copy of the files, as the
267 // URL changed.
268 $query_string = '?' . variable_get('css_js_query_string', '0');
269
270 $script .= 'ga.src = "' . $url . $query_string . '";';
271 }
272 else {
273 $script .= 'ga.src = ("https:" == document.location.protocol ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";';
274 }
275 $script .= 'var s = document.getElementsByTagName("script")[0];';
276 $script .= 's.parentNode.insertBefore(ga, s);';
277 $script .= '})();';
278
279 drupal_add_js($script, array('scope' => $scope, 'type' => 'inline'));
280 }
281 }
282
283 /**
284 * Implements hook_form_FORM_ID_alter().
285 *
286 * Allow users to decide if tracking code will be added to pages or not.
287 */
288 function googleanalytics_form_user_profile_form_alter(&$form, &$form_state) {
289 $account = $form['#user'];
290 $category = $form['#user_category'];
291
292 if ($category == 'account' && user_access('opt-in or out of tracking') && ($custom = variable_get('googleanalytics_custom', 0)) != 0 && _googleanalytics_visibility_roles($account)) {
293 $form['googleanalytics'] = array(
294 '#type' => 'fieldset',
295 '#title' => t('Google Analytics configuration'),
296 '#weight' => 3,
297 '#collapsible' => TRUE,
298 '#tree' => TRUE
299 );
300
301 switch ($custom) {
302 case 1:
303 $description = t('Users are tracked by default, but you are able to opt out.');
304 break;
305
306 case 2:
307 $description = t('Users are <em>not</em> tracked by default, but you are able to opt in.');
308 break;
309 }
310
311 $form['googleanalytics']['custom'] = array(
312 '#type' => 'checkbox',
313 '#title' => t('Enable user tracking'),
314 '#description' => $description,
315 '#default_value' => isset($account->data['googleanalytics']['custom']) ? $account->data['googleanalytics']['custom'] : ($custom == 1)
316 );
317
318 return $form;
319 }
320 }
321
322 /**
323 * Implements hook_user_presave().
324 */
325 function googleanalytics_user_presave(&$edit, $account, $category) {
326 if (isset($edit['googleanalytics']['custom'])) {
327 $edit['data']['googleanalytics']['custom'] = $edit['googleanalytics']['custom'];
328 }
329 }
330
331 /**
332 * Implements hook_cron().
333 */
334 function googleanalytics_cron() {
335 // Regenerate the tracking code file every day.
336 if (REQUEST_TIME - variable_get('googleanalytics_last_cache', 0) >= 86400 && variable_get('googleanalytics_cache', 0)) {
337 _googleanalytics_cache('http://www.google-analytics.com/ga.js', TRUE);
338 variable_set('googleanalytics_last_cache', REQUEST_TIME);
339 }
340 }
341
342 /**
343 * Download/Synchronize/Cache tracking code file locally.
344 *
345 * @param $location
346 * The full URL to the external javascript file.
347 * @param $sync_cached_file
348 * Synchronize tracking code and update if remote file have changed.
349 * @return mixed
350 * The path to the local javascript file on success, boolean FALSE on failure.
351 */
352 function _googleanalytics_cache($location, $sync_cached_file = FALSE) {
353 $path = 'public://googleanalytics';
354 $file_destination = $path . '/' . basename($location);
355
356 if (!file_exists($file_destination) || $sync_cached_file) {
357 // Download the latest tracking code.
358 $result = drupal_http_request($location);
359
360 if ($result->code == 200) {
361 if (file_exists($file_destination)) {
362 // Synchronize tracking code and and replace local file if outdated.
363 $data_hash_local = drupal_hash_base64(file_get_contents($file_destination));
364 $data_hash_remote = drupal_hash_base64($result->data);
365 // Check that the files directory is writable.
366 if ($data_hash_local != $data_hash_remote && file_prepare_directory($path)) {
367 // Save updated tracking code file to disk.
368 file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
369 watchdog('googleanalytics', 'Locally cached tracking code file has been updated.', array(), WATCHDOG_INFO);
370
371 // Change query-strings on css/js files to enforce reload for all users.
372 _drupal_flush_css_js();
373 }
374 }
375 else {
376 // Check that the files directory is writable.
377 if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
378 // There is no need to flush JS here as core refreshes JS caches
379 // automatically, if new files are added.
380 file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
381 watchdog('googleanalytics', 'Locally cached tracking code file has been saved.', array(), WATCHDOG_INFO);
382
383 // Return the local JS file path.
384 return file_create_url($file_destination);
385 }
386 }
387 }
388 }
389 else {
390 // Return the local JS file path.
391 return file_create_url($file_destination);
392 }
393 }
394
395 /**
396 * Delete cached files and directory.
397 */
398 function googleanalytics_clear_js_cache() {
399 $path = 'public://googleanalytics';
400 if (file_prepare_directory($path)) {
401 file_scan_directory($path, '/.*/', array('callback' => 'file_unmanaged_delete'));
402 drupal_rmdir($path);
403
404 // Change query-strings on css/js files to enforce reload for all users.
405 _drupal_flush_css_js();
406
407 watchdog('googleanalytics', 'Local cache has been purged.', array(), WATCHDOG_INFO);
408 }
409 }
410
411 /**
412 * Helper function for grabbing search keys. Function is missing in D7.
413 *
414 * http://api.drupal.org/api/function/search_get_keys/6
415 */
416 function googleanalytics_search_get_keys() {
417 static $return;
418 if (!isset($return)) {
419 // Extract keys as remainder of path
420 // Note: support old GET format of searches for existing links.
421 $path = explode('/', $_GET['q'], 3);
422 $keys = empty($_REQUEST['keys']) ? '' : $_REQUEST['keys'];
423 $return = count($path) == 3 ? $path[2] : $keys;
424 }
425 return $return;
426 }
427
428 /**
429 * Tracking visibility check for an user object.
430 *
431 * @param $account
432 * A user object containing an array of roles to check.
433 * @return boolean
434 * A decision on if the current user is being tracked by Google Analytics.
435 */
436 function _googleanalytics_visibility_user($account) {
437
438 $enabled = FALSE;
439
440 // Is current user a member of a role that should be tracked?
441 if (_googleanalytics_visibility_roles($account)) {
442
443 // Use the user's block visibility setting, if necessary.
444 if (($custom = variable_get('googleanalytics_custom', 0)) != 0) {
445 if ($account->uid && isset($account->data['googleanalytics']['custom'])) {
446 $enabled = $account->data['googleanalytics']['custom'];
447 }
448 else {
449 $enabled = ($custom == 1);
450 }
451 }
452 else {
453 $enabled = TRUE;
454 }
455
456 }
457
458 return $enabled;
459 }
460
461 /**
462 * Based on visibility setting this function returns TRUE if GA code should
463 * be added for the current role and otherwise FALSE.
464 */
465 function _googleanalytics_visibility_roles($account) {
466
467 $visibility = variable_get('googleanalytics_visibility_roles', 0);
468 $enabled = $visibility;
469 $roles = variable_get('googleanalytics_roles', array());
470
471 if (array_sum($roles) > 0) {
472 // One or more roles are selected.
473 foreach (array_keys($account->roles) as $rid) {
474 // Is the current user a member of one of these roles?
475 if (isset($roles[$rid]) && $rid == $roles[$rid]) {
476 // Current user is a member of a role that should be tracked/excluded from tracking.
477 $enabled = !$visibility;
478 break;
479 }
480 }
481 }
482 else {
483 // No role is selected for tracking, therefore all roles should be tracked.
484 $enabled = TRUE;
485 }
486
487 return $enabled;
488 }
489
490 /**
491 * Based on visibility setting this function returns TRUE if GA code should
492 * be added to the current page and otherwise FALSE.
493 */
494 function _googleanalytics_visibility_pages() {
495 static $page_match;
496
497 // Cache visibility result if function is called more than once.
498 if (!isset($page_match)) {
499
500 $visibility = variable_get('googleanalytics_visibility_pages', 0);
501 $setting_pages = variable_get('googleanalytics_pages', '');
502
503 // Match path if necessary.
504 if (!empty($setting_pages)) {
505 // Convert path to lowercase. This allows comparison of the same path
506 // with different case. Ex: /Page, /page, /PAGE.
507 $pages = drupal_strtolower($setting_pages);
508 if ($visibility < 2) {
509 // Convert the Drupal path to lowercase
510 $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
511 // Compare the lowercase internal and lowercase path alias (if any).
512 $page_match = drupal_match_path($path, $pages);
513 if ($path != $_GET['q']) {
514 $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
515 }
516 // When $visibility has a value of 0, the tracking code is displayed on
517 // all pages except those listed in $pages. When set to 1, it
518 // is displayed only on those pages listed in $pages.
519 $page_match = !($visibility xor $page_match);
520 }
521 elseif (module_exists('php')) {
522 $page_match = php_eval($setting_pages);
523 }
524 else {
525 $page_match = FALSE;
526 }
527 }
528 else {
529 $page_match = TRUE;
530 }
531
532 }
533 return $page_match;
534 }