summaryrefslogtreecommitdiffstats
path: root/googleanalytics.module
blob: b17f9c80fbed5dd76de630db1b14b261dc675377 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
<?php
// $Id$

/*
 * @file
 * Drupal Module: GoogleAnalytics
 * Adds the required Javascript to the bottom of all your Drupal pages
 * to allow tracking by the Google Analytics statistics package.
 *
 * @author: Mike Carter <www.ixis.co.uk/contact>
 */

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');

function googleanalytics_help($path, $arg) {
  switch ($path) {
    case 'admin/settings/googleanalytics':
      return t('<a href="@ga_url">Google Analytics</a> is a free statistics package based on the excellent Urchin system. This module provides services to better integrate Drupal with Google Analytics.', array('@ga_url' => 'http://www.google.com/analytics/'));
  }
}

function googleanalytics_perm() {
  return array(
    'administer google analytics' => array(
      'title' => t('Administer Google Analytics'),
      'description' => t('Perform maintenance tasks for Google Analytics.'),
    ),
    'opt-in or out of tracking' => array(
      'title' => t('Opt-in or out of tracking'),
      'description' => t('Allow users to decide if tracking code will be added to pages or not.'),
    ),
    'use PHP for tracking visibility' => array(
      'title' => t('Use PHP for tracking visibility'),
      '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.'))),
    ),
  );  
}

function googleanalytics_menu() {
  $items['admin/settings/googleanalytics'] = array(
    'title' => 'Google Analytics',
    'description' => 'Configure the settings used to generate your Google Analytics tracking code.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('googleanalytics_admin_settings_form'),
    'access arguments' => array('administer google analytics'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function googleanalytics_init() {
  global $user;

  $id = variable_get('googleanalytics_account', '');

  // 1. Check if the GA account number has a value.
  // 2. Track page views based on visibility value.
  // 3. Check if we should track the currently active user's role.
  if (!empty($id) && _googleanalytics_visibility_pages() && _googleanalytics_visibility_user($user)) {
    $scope = variable_get('googleanalytics_js_scope', 'footer');

    // Should a local cached copy of ga.js be used?
    $js_file = 'ga.js';
    $url = 'http://www.google-analytics.com/'. $js_file;

    if (variable_get('googleanalytics_cache', 0) && (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC) && $source = _googleanalytics_cache($url)) {
      drupal_add_js($source, array('type' => 'file', 'scope' => $scope));
    }
    else {
      $script = 'var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");';
      $script .= 'document.write(unescape("%3Cscript src=\'" + gaJsHost + "google-analytics.com/'. $js_file .'\' type=\'text/javascript\'%3E%3C/script%3E"));';
      drupal_add_js($script, array('type' => 'inline', 'scope' => $scope, 'weight' => JS_DEFAULT - 1));
    }

    // Add link tracking.
    $link_settings = array();
    if ($track_outgoing = variable_get('googleanalytics_trackoutgoing', 1)) {
      $link_settings['trackOutgoing'] = $track_outgoing;
    }
    if ($track_mailto = variable_get('googleanalytics_trackmailto', 1)) {
      $link_settings['trackMailto'] = $track_mailto;
    }
    if (($track_download = variable_get('googleanalytics_trackfiles', 1)) && ($trackfiles_extensions = variable_get('googleanalytics_trackfiles_extensions', GA_TRACKFILES_EXTENSIONS))) {
      $link_settings['trackDownload'] = $track_download;
      $link_settings['trackDownloadExtensions'] = $trackfiles_extensions;
    }
    if (!empty($link_settings)) {
      drupal_add_js(array('googleanalytics' => $link_settings), array('type' => 'setting', 'scope' => 'header'));
      drupal_add_js(drupal_get_path('module', 'googleanalytics') .'/googleanalytics.js', array('type' => 'file', 'scope' => $scope));
    }

    // Custom tracking.
    if (variable_get('googleanalytics_trackadsense', FALSE)) {
      drupal_add_js('window.google_analytics_uacct = ' . drupal_to_js($id) . ';', 'inline', 'header');
    }
  }
}

/**
 * Implementation of hook_footer() to insert Javascript at the end of the page.
 */
function googleanalytics_footer($main = 0) {
  global $user;

  $id = variable_get('googleanalytics_account', '');

  if (!empty($id) && _googleanalytics_visibility_pages() && _googleanalytics_visibility_user($user)) {

    // Add User profile segmentation values.
    if (is_array($profile_fields = variable_get('googleanalytics_segmentation', '')) && ($user->uid > 0)) {

      $p = module_invoke('profile', 'load_profile', $user);

      $fields = array();
      foreach ($profile_fields as $field => $title) {
        $value = $user->$field;

        if (is_array($value)) {
          $value = implode(',', $value);
        }

        $fields[$field] = $value;
      }

      // Only show segmentation variable if there are specified fields.
      $segmentation = '';
      if (count($fields) > 0) {
        $segmentation = 'pageTracker._setVar('. drupal_to_js(implode(':', $fields)) .');';
      }
    }

    // Site search tracking support.
    $url_custom = '';
    if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE) && arg(0) == 'search' && $keys = search_get_keys()) {
      $url_custom = drupal_to_js(url('search/'. arg(1), array('query' => 'search='. $keys)));
    }

    // If this node is a translation of another node, pass the original
    // node instead.
    if (module_exists('translation') && variable_get('googleanalytics_translation_set', 0)) {
      // Check we have a node object, it supports translation, and its
      // translated node ID (tnid) doesn't match its own node ID.
      $node = menu_get_object();
      if ($node && translation_supported_type($node->type) && isset($node->tnid) && ($node->tnid != $node->nid)) {
        $source_node = node_load($node->tnid);
        $languages = language_list();
        $url_custom = drupal_to_js(url('node/'. $source_node->nid, array('language' => $languages[$source_node->language])));
      }
    }

    // Track access denied (403) and file not found (404) pages.
    if (function_exists('drupal_get_headers')) {
      $headers = drupal_get_headers();
      if (strstr($headers, 'HTTP/1.1 403 Forbidden')) {
        // See http://www.google.com/support/analytics/bin/answer.py?answer=86927
        $url_custom = '"/403.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
      }
      elseif (strstr($headers, 'HTTP/1.1 404 Not Found')) {
        $url_custom = '"/404.html?page=" + document.location.pathname + document.location.search + "&from=" + document.referrer';
      }
    }

    // Add any custom code snippets if specified.
    $codesnippet_before = variable_get('googleanalytics_codesnippet_before', '');
    $codesnippet_after = variable_get('googleanalytics_codesnippet_after', '');

    // Build tracker code for footer.
    $script = 'try{';
    $script .= 'var pageTracker = _gat._getTracker('. drupal_to_js($id) .');';
    if (!empty($segmentation)) {
      $script .= $segmentation;
    }
    if (!empty($codesnippet_before)) {
      $script .= $codesnippet_before;
    }
    $script .= 'pageTracker._trackPageview('. $url_custom .');';
    if (!empty($codesnippet_after)) {
      $script .= $codesnippet_after;
    }
    $script .= '} catch(err) {}';

    drupal_add_js($script, array('type' => 'inline', 'scope' => 'footer'));
  }
}

/**
 * Implementation of hook_user().
 *
 * Allow users to decide if tracking code will be added to pages or not.
 */
function googleanalytics_user_form(&$edit, &$account, $category = NULL) {
  if ($category == 'account' && user_access('opt-in or out of tracking') && ($custom = variable_get('googleanalytics_custom', 0)) != 0 && _googleanalytics_visibility_roles($account)) {
    $form['googleanalytics'] = array(
      '#type' => 'fieldset',
      '#title' => t('Google Analytics configuration'),
      '#weight' => 3,
      '#collapsible' => TRUE,
      '#tree' => TRUE
    );

    switch ($custom) {
      case 1:
        $description = t('Users are tracked by default, but you are able to opt out.');
        break;

      case 2:
        $description = t('Users are <em>not</em> tracked by default, but you are able to opt in.');
        break;
    }

    $form['googleanalytics']['custom'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable user tracking'),
      '#description' => $description,
      '#default_value' => isset($account->googleanalytics['custom']) ? $account->googleanalytics['custom'] : ($custom == 1)
    );

    return $form;
  }
}

/**
 * Implementation of hook_requirements().
 */
function googleanalytics_requirements($phase) {
  $requirements = array();

  if ($phase == 'runtime') {
    // Raise warning if Google user account has not been set yet.
    if (!preg_match('/^UA-\d{4,}-\d+$/', variable_get('googleanalytics_account', 'UA-'))) {
      $requirements['googleanalytics'] = array(
        'title' => t('Google Analytics module'),
        'description' => t('Google Analytics module has not been configured yet. Please configure its settings from the <a href="@url">Google Analytics settings page</a>.', array('@url' => url('admin/settings/googleanalytics'))),
        'severity' => REQUIREMENT_ERROR,
        'value' => t('Not configured'),
      );
    }
  }

  return $requirements;
}

/**
 * Implementation of hook_cron().
 */
function googleanalytics_cron() {
  // Regenerate the google analytics ga.js every day.
  if (time() - variable_get('googleanalytics_last_cache', 0) >= 86400) {
    // New google analytics version.
    file_unmanaged_delete(file_directory_path() .'/googleanalytics/ga.js');

    // Clear aggregated JS files.
    if (variable_get('preprocess_js', 0)) {
      drupal_clear_js_cache();
    }

    variable_set('googleanalytics_last_cache', time());
  }
}

/**
 * Download and cache the ga.js file locally.
 * @param $location
 *   The full URL to the external javascript file.
 * @return mixed
 *   The path to the local javascript file on success, boolean FALSE on failure.
 */
function _googleanalytics_cache($location) {
  $directory = file_directory_path() .'/googleanalytics';
  $file_destination = $directory .'/'. basename($location);
  if (!file_exists($file_destination)) {
    $result = drupal_http_request($location);
    if ($result->code == 200) {
      // Check that the files directory is writable
      if (file_check_directory($directory, FILE_CREATE_DIRECTORY)) {
        return file_unmanaged_save_data($result->data, $directory .'/'. basename($location), FILE_EXISTS_REPLACE);
      }
    }
  }
  else {
    return $file_destination;
  }
}

/**
 * Tracking visibility check for an user object.
 *
 * @param $account
 *   A user object containing an array of roles to check.
 * @return boolean
 *   A decision on if the current user is being tracked by Google Analytics.
 */
function _googleanalytics_visibility_user($account) {

  $enabled = FALSE;

  // Is current user a member of a role that should be tracked?
  if (_googleanalytics_visibility_roles($account)) {

    // Use the user's block visibility setting, if necessary.
    if (($custom = variable_get('googleanalytics_custom', 0)) != 0) {
      if ($account->uid && isset($account->googleanalytics['custom'])) {
        $enabled = $account->googleanalytics['custom'];
      }
      else {
        $enabled = ($custom == 1);
      }
    }
    else {
      $enabled = TRUE;
    }

  }

  return $enabled;
}

/**
 * Based on visibility setting this function returns TRUE if GA code should
 * be added for the current role and otherwise FALSE.
 */
function _googleanalytics_visibility_roles($account) {

  $enabled = FALSE;
  $roles = variable_get('googleanalytics_roles', array());

  if (array_sum($roles) > 0) {
    // One or more roles are selected for tracking.
    foreach (array_keys($account->roles) as $rid) {
      // Is the current user a member of one role enabled for tracking?
      if (isset($roles[$rid]) && $rid == $roles[$rid]) {
        // Current user is a member of a role that should be tracked.
        $enabled = TRUE;
        break;
      }
    }
  }
  else {
    // No role is selected for tracking, therefor all roles should be tracked.
    $enabled = TRUE;
  }

  return $enabled;
}

/**
 * Based on visibility setting this function returns TRUE if GA code should
 * be added to the current page and otherwise FALSE.
 */
function _googleanalytics_visibility_pages() {
  static $page_match;

  // Cache visibility setting in hook_init for hook_footer.
  if (!isset($page_match)) {

    $visibility = variable_get('googleanalytics_visibility', 0);
    $pages = variable_get('googleanalytics_pages', '');

    // Match path if necessary.
    if (!empty($pages)) {
      if ($visibility < 2) {
        $path = drupal_get_path_alias($_GET['q']);
        // Compare with the internal and path alias (if any).
        $page_match = drupal_match_path($path, $pages);
        if ($path != $_GET['q']) {
          $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
        }
        // When $visibility has a value of 0, the block is displayed on
        // all pages except those listed in $pages. When set to 1, it
        // is displayed only on those pages listed in $pages.
        $page_match = !($visibility xor $page_match);
      }
      else {
        $page_match = drupal_eval($pages);
      }
    }
    else {
      $page_match = TRUE;
    }

  }
  return $page_match;
}