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