googleanalytics.module 22.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
<?php

/*
 * @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: Alexander Hass <http://drupal.org/user/85918>
 */

hass's avatar
hass committed
12
define('GOOGLEANALYTICS_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
16
// Remove tracking from all administrative pages, see http://drupal.org/node/34970.
define('GOOGLEANALYTICS_PAGES', "admin\nadmin/*\nbatch\nnode/add*\nnode/*/*\nuser/*/*");

17
18
19
/**
 * Implements hook_help().
 */
20
21
22
23
24
25
26
27
function googleanalytics_help($path, $arg) {
  switch ($path) {
    case 'admin/config/system/googleanalytics':
      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/'));
  }
}

/**
28
 * Implements hook_theme().
29
30
31
32
33
34
35
36
37
 */
function googleanalytics_theme() {
  return array(
    'googleanalytics_admin_custom_var_table' => array(
      'render element' => 'form',
    ),
  );
}

38
39
40
/**
 * Implements hook_permission().
 */
41
42
43
44
45
46
47
48
49
50
51
52
function googleanalytics_permission() {
  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'),
53
54
      'description' => t('Enter PHP code in the field for tracking visibility settings.'),
      'restrict access' => TRUE,
55
56
57
58
    ),
  );
}

59
60
61
/**
 * Implements hook_menu().
 */
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
function googleanalytics_menu() {
  $items['admin/config/system/googleanalytics'] = array(
    'title' => 'Google Analytics',
    'description' => 'Configure tracking behavior to get insights into your website traffic and marketing effectiveness.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('googleanalytics_admin_settings_form'),
    'access arguments' => array('administer google analytics'),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'googleanalytics.admin.inc',
  );

  return $items;
}

/**
77
 * Implements hook_page_alter() to insert JavaScript to the appropriate scope/region of the page.
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
 */
function googleanalytics_page_alter(&$page) {
  global $user;

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

  // Get page status code for visibility filtering.
  $status = drupal_get_http_header('Status');
  $trackable_status_codes = array(
    '403 Forbidden',
    '404 Not Found',
  );

  // 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.
  // 4. Ignore pages visibility filter for 404 or 403 status codes.
  if (!empty($id) && (_googleanalytics_visibility_pages() || in_array($status, $trackable_status_codes)) && _googleanalytics_visibility_user($user)) {

    // We allow different scopes. Default to 'header' but allow user to override if they really need to.
    $scope = variable_get('googleanalytics_js_scope', 'header');

    if (variable_get('googleanalytics_trackadsense', FALSE)) {
      // Custom tracking. Prepend before all other JavaScript.
      drupal_add_js('window.google_analytics_uacct = ' . drupal_json_encode($id) . ';', array('type' => 'inline', 'group' => JS_LIBRARY-1));
    }

    // Add link tracking.
    $link_settings = array();
107
108
    if ($track_outbound = variable_get('googleanalytics_trackoutbound', 1)) {
      $link_settings['trackOutbound'] = $track_outbound;
109
110
111
112
    }
    if ($track_mailto = variable_get('googleanalytics_trackmailto', 1)) {
      $link_settings['trackMailto'] = $track_mailto;
    }
hass's avatar
hass committed
113
    if (($track_download = variable_get('googleanalytics_trackfiles', 1)) && ($trackfiles_extensions = variable_get('googleanalytics_trackfiles_extensions', GOOGLEANALYTICS_TRACKFILES_EXTENSIONS))) {
114
115
116
      $link_settings['trackDownload'] = $track_download;
      $link_settings['trackDownloadExtensions'] = $trackfiles_extensions;
    }
117
118
119
120
121
122
123
124
    if ($track_domain_mode = variable_get('googleanalytics_domain_mode', 0)) {
      $link_settings['trackDomainMode'] = $track_domain_mode;
    }
    if ($track_cross_domains = variable_get('googleanalytics_cross_domains', '')) {
      $domains = preg_split('/(\r\n?|\n)/', $track_cross_domains);
      $link_settings['trackCrossDomains'] = implode('|', $domains);
    }

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
    if (!empty($link_settings)) {
      drupal_add_js(array('googleanalytics' => $link_settings), 'setting');
      drupal_add_js(drupal_get_path('module', 'googleanalytics') . '/googleanalytics.js');
    }

    // Add User profile segmentation values.
    $profile_fields = variable_get('googleanalytics_segmentation', array());
    if (!empty($profile_fields)) {
      // Invoke all modules having a hook_user_load() implemented.
      // If the invoked modules extend the $user object, the additional
      // data can be tracked.
      module_invoke_all('user_load', array($user->uid => $user));

      $fields = array();
      foreach ($profile_fields as $field => $title) {
        $fields[$field] = is_array($user->$field) ? implode(',', $user->$field) : $user->$field;
      }

      // Only show segmentation variable if there are specified fields.
      $segmentation = '';
      if (count($fields) > 0) {
        $segmentation = '_gaq.push(["_setVar", ' . drupal_json_encode(implode(':', $fields)) . ']);';
      }
    }

    // Site search tracking support.
    $url_custom = '';
    if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE) && arg(0) == 'search' && $keys = googleanalytics_search_get_keys()) {
hass's avatar
hass committed
153
      $url_custom = '(window.googleanalytics_search_results) ? ' . drupal_json_encode(url('search/' . arg(1), array('query' => array('search' => $keys)))) . ' : ' . drupal_json_encode(url('search/' . arg(1), array('query' => array('search' => 'no-results:' . $keys, 'cat' => 'no-results'))));
154
155
156
157
158
159
160
161
    }

    // 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();
162
      if ($node && translation_supported_type($node->type) && !empty($node->tnid) && ($node->tnid != $node->nid)) {
163
164
        $source_node = node_load($node->tnid);
        $languages = language_list();
165
        $url_custom = drupal_json_encode(url('node/' . $source_node->nid, array('language' => $languages[$source_node->language])));
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
      }
    }

    // Track access denied (403) and file not found (404) pages.
    if ($status == '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 ($status == '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', '');

    // Add custom variables.
    $googleanalytics_custom_vars = variable_get('googleanalytics_custom_var', array());
    $custom_var = '';
    for ($i = 1; $i < 6; $i++) {
      $custom_var_name = !empty($googleanalytics_custom_vars['slots'][$i]['name']) ? $googleanalytics_custom_vars['slots'][$i]['name'] : '';
      if (!empty($custom_var_name)) {
        $custom_var_value = !empty($googleanalytics_custom_vars['slots'][$i]['value']) ? $googleanalytics_custom_vars['slots'][$i]['value'] : '';
        $custom_var_scope = !empty($googleanalytics_custom_vars['slots'][$i]['scope']) ? $googleanalytics_custom_vars['slots'][$i]['scope'] : 3;

191
        $types = array();
192
        $node = menu_get_object();
193
194
195
        if (is_object($node)) {
          $types += array('node' => $node);
        }
196
        $custom_var_name = token_replace($custom_var_name, $types, array('clear' => TRUE));
197
        $custom_var_value = token_replace($custom_var_value, $types, array('clear' => TRUE));
198

199
200
        // Suppress empty custom names and/or variables.
        if (!drupal_strlen(trim($custom_var_name)) || !drupal_strlen(trim($custom_var_value))) {
201
202
          continue;
        }
203
204

        // The length of the string used for the 'name' and the length of the
205
        // string used for the 'value' must not exceed 128 bytes after url encoding.
206
        $name_length = drupal_strlen(rawurlencode($custom_var_name));
207
        $tmp_value = rawurlencode($custom_var_value);
208
        $value_length = drupal_strlen($tmp_value);
209
        if ($name_length + $value_length > 128) {
210
          // Trim value and remove fragments of url encoding.
211
          $tmp_value = rtrim(substr($tmp_value, 0, 127 - $name_length), '%0..9A..F');
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
          $custom_var_value = urldecode($tmp_value);
        }

        $custom_var_name = drupal_json_encode($custom_var_name);
        $custom_var_value = drupal_json_encode($custom_var_value);
        $custom_var .= "_gaq.push(['_setCustomVar', $i, $custom_var_name, $custom_var_value, $custom_var_scope]);";
      }
    }

    // Build tracker code.
    $script = 'var _gaq = _gaq || [];';
    $script .= '_gaq.push(["_setAccount", ' . drupal_json_encode($id) . ']);';
    if (variable_get('googleanalytics_tracker_anonymizeip', 0)) {
      // FIXME: The Google API is currently broken and "_gat._anonymizeIp" is only
      // a workaround until "_anonymizeIp" has been implemented/fixed.
      $script .= '_gaq.push(["_gat._anonymizeIp"]);';
    }
229
230
231
232
233
234
235
236
237
238

    // Domain tracking type.
    global $cookie_domain;
    $domain_mode = variable_get('googleanalytics_domain_mode', 0);

    // Per RFC 2109, cookie domains must contain at least one dot other than the
    // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
    if ($domain_mode == 1 && count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
      $script .= '_gaq.push(["_setDomainName", ' . drupal_json_encode($cookie_domain) . ']);';
    }
239
    elseif ($domain_mode == 2) {
240
241
242
243
      $script .= '_gaq.push(["_setDomainName", "none"]);';
      $script .= '_gaq.push(["_setAllowLinker", true]);';
    }

244
245
246
247
248
249
    if (!empty($segmentation)) {
      $script .= $segmentation;
    }
    if (!empty($custom_var)) {
      $script .= $custom_var;
    }
250
251
252
    if (!empty($codesnippet_before)) {
      $script .= $codesnippet_before;
    }
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
    if (empty($url_custom)) {
      $script .= '_gaq.push(["_trackPageview"]);';
    }
    else {
      $script .= '_gaq.push(["_trackPageview", ' . $url_custom . ']);';
    }
    if (!empty($codesnippet_after)) {
      $script .= $codesnippet_after;
    }

    $script .= '(function() {';
    $script .= 'var ga = document.createElement("script");';
    $script .= 'ga.type = "text/javascript";';
    $script .= 'ga.async = true;';

    // Should a local cached copy of ga.js be used?
    if (variable_get('googleanalytics_cache', 0) && $url = _googleanalytics_cache('http://www.google-analytics.com/ga.js')) {
270
271
272
273
274
275
      // A dummy query-string is added to filenames, to gain control over
      // browser-caching. The string changes on every update or full cache
      // flush, forcing browsers to load a new copy of the files, as the
      // URL changed.
      $query_string = '?' . variable_get('css_js_query_string', '0');

276
277
278
279
280
281
282
283
284
285
286
287
288
      $script .= 'ga.src = "' . $url . $query_string . '";';
    }
    else {
      $script .= 'ga.src = ("https:" == document.location.protocol ? "https://ssl" : "http://www") + ".google-analytics.com/ga.js";';
    }
    $script .= 'var s = document.getElementsByTagName("script")[0];';
    $script .= 's.parentNode.insertBefore(ga, s);';
    $script .= '})();';

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

hass's avatar
hass committed
289
290
291
292
293
294
295
296
297
298
299
300
301
/**
 * Implements hook_field_extra_fields().
 */
function googleanalytics_field_extra_fields() {
  $extra['user']['user']['form']['googleanalytics'] = array(
      'label' => t('Google Analytics configuration'),
      'description' => t('Google Analytics module form element.'),
      'weight' => 3,
  );

  return $extra;
}

302
/**
303
 * Implements hook_form_FORM_ID_alter().
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
 *
 * Allow users to decide if tracking code will be added to pages or not.
 */
function googleanalytics_form_user_profile_form_alter(&$form, &$form_state) {
  $account = $form['#user'];
  $category = $form['#user_category'];

  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;
    }

330
331
332
333
334
335
336
337
338
339
340
341
342
    // Disable tracking for visitors who have opted out from tracking via DNT (Do-Not-Track) header.
    $disabled = FALSE;
    if (variable_get('googleanalytics_privacy_donottrack', 1) && !empty($_SERVER['HTTP_DNT'])) {
      $disabled = TRUE;

      // Override settings value.
      $account->data['googleanalytics']['custom'] = FALSE;

      $description .= '<span class="admin-disabled">';
      $description .= ' ' . t('You have opted out from tracking via browser privacy settings.');
      $description .= '</span>';
    }

343
344
345
346
    $form['googleanalytics']['custom'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable user tracking'),
      '#description' => $description,
347
348
      '#default_value' => isset($account->data['googleanalytics']['custom']) ? $account->data['googleanalytics']['custom'] : ($custom == 1),
      '#disabled' => $disabled,
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
    );

    return $form;
  }
}

/**
 * Implements hook_user_presave().
 */
function googleanalytics_user_presave(&$edit, $account, $category) {
  if (isset($edit['googleanalytics']['custom'])) {
    $edit['data']['googleanalytics']['custom'] = $edit['googleanalytics']['custom'];
  }
}

/**
365
 * Implements hook_cron().
366
367
368
 */
function googleanalytics_cron() {
  // Regenerate the tracking code file every day.
369
  if (REQUEST_TIME - variable_get('googleanalytics_last_cache', 0) >= 86400 && variable_get('googleanalytics_cache', 0)) {
370
    _googleanalytics_cache('http://www.google-analytics.com/ga.js', TRUE);
371
    variable_set('googleanalytics_last_cache', REQUEST_TIME);
372
373
374
  }
}

hass's avatar
hass committed
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
/**
 * Implements hook_preprocess_search_results().
 *
 * Collects and adds the number of search results to the head.
 */
function googleanalytics_preprocess_search_results(&$variables) {
  // There is no search result $variable available that hold the number of items
  // found. But the pager item mumber can tell the number of search results.
  global $pager_total_items;

  drupal_add_js('window.googleanalytics_search_results = ' . intval($pager_total_items[0]) . ';', array('type' => 'inline', 'group' => JS_LIBRARY-1));
}

/**
 * Helper function for grabbing search keys. Function is missing in D7.
 *
 * http://api.drupal.org/api/function/search_get_keys/6
 */
function googleanalytics_search_get_keys() {
  static $return;
  if (!isset($return)) {
    // Extract keys as remainder of path
    // Note: support old GET format of searches for existing links.
    $path = explode('/', $_GET['q'], 3);
    $keys = empty($_REQUEST['keys']) ? '' : $_REQUEST['keys'];
    $return = count($path) == 3 ? $path[2] : $keys;
  }
  return $return;
}

405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
/**
 * Download/Synchronize/Cache tracking code file locally.
 *
 * @param $location
 *   The full URL to the external javascript file.
 * @param $sync_cached_file
 *   Synchronize tracking code and update if remote file have changed.
 * @return mixed
 *   The path to the local javascript file on success, boolean FALSE on failure.
 */
function _googleanalytics_cache($location, $sync_cached_file = FALSE) {
  $path = 'public://googleanalytics';
  $file_destination = $path . '/' . basename($location);

  if (!file_exists($file_destination) || $sync_cached_file) {
    // Download the latest tracking code.
    $result = drupal_http_request($location);

    if ($result->code == 200) {
      if (file_exists($file_destination)) {
        // Synchronize tracking code and and replace local file if outdated.
        $data_hash_local = drupal_hash_base64(file_get_contents($file_destination));
        $data_hash_remote = drupal_hash_base64($result->data);
        // Check that the files directory is writable.
        if ($data_hash_local != $data_hash_remote && file_prepare_directory($path)) {
          // Save updated tracking code file to disk.
          file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
          watchdog('googleanalytics', 'Locally cached tracking code file has been updated.', array(), WATCHDOG_INFO);

          // Change query-strings on css/js files to enforce reload for all users.
          _drupal_flush_css_js();
        }
      }
      else {
        // Check that the files directory is writable.
        if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
          // There is no need to flush JS here as core refreshes JS caches
          // automatically, if new files are added.
          file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
          watchdog('googleanalytics', 'Locally cached tracking code file has been saved.', array(), WATCHDOG_INFO);

          // Return the local JS file path.
          return file_create_url($file_destination);
        }
      }
    }
  }
  else {
    // Return the local JS file path.
    return file_create_url($file_destination);
  }
}

/**
 * Delete cached files and directory.
 */
function googleanalytics_clear_js_cache() {
  $path = 'public://googleanalytics';
  if (file_prepare_directory($path)) {
    file_scan_directory($path, '/.*/', array('callback' => 'file_unmanaged_delete'));
    drupal_rmdir($path);

    // Change query-strings on css/js files to enforce reload for all users.
    _drupal_flush_css_js();

    watchdog('googleanalytics', 'Local cache has been purged.', array(), WATCHDOG_INFO);
  }
}

/**
 * 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?
487
  if (_googleanalytics_visibility_header($account) && _googleanalytics_visibility_roles($account)) {
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512

    // Use the user's block visibility setting, if necessary.
    if (($custom = variable_get('googleanalytics_custom', 0)) != 0) {
      if ($account->uid && isset($account->data['googleanalytics']['custom'])) {
        $enabled = $account->data['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) {

513
514
  $visibility = variable_get('googleanalytics_visibility_roles', 0);
  $enabled = $visibility;
515
516
517
  $roles = variable_get('googleanalytics_roles', array());

  if (array_sum($roles) > 0) {
518
    // One or more roles are selected.
519
    foreach (array_keys($account->roles) as $rid) {
520
      // Is the current user a member of one of these roles?
521
      if (isset($roles[$rid]) && $rid == $roles[$rid]) {
522
523
        // Current user is a member of a role that should be tracked/excluded from tracking.
        $enabled = !$visibility;
524
525
526
527
528
        break;
      }
    }
  }
  else {
529
    // No role is selected for tracking, therefore all roles should be tracked.
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
    $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 result if function is called more than once.
  if (!isset($page_match)) {

546
    $visibility = variable_get('googleanalytics_visibility_pages', 0);
547
    $setting_pages = variable_get('googleanalytics_pages', GOOGLEANALYTICS_PAGES);
548
549

    // Match path if necessary.
550
551
552
553
    if (!empty($setting_pages)) {
      // Convert path to lowercase. This allows comparison of the same path
      // with different case. Ex: /Page, /page, /PAGE.
      $pages = drupal_strtolower($setting_pages);
554
      if ($visibility < 2) {
555
556
557
        // Convert the Drupal path to lowercase
        $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
        // Compare the lowercase internal and lowercase path alias (if any).
558
559
560
561
        $page_match = drupal_match_path($path, $pages);
        if ($path != $_GET['q']) {
          $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
        }
562
        // When $visibility has a value of 0, the tracking code is displayed on
563
564
565
566
        // 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);
      }
567
568
569
      elseif (module_exists('php')) {
        $page_match = php_eval($setting_pages);
      }
570
      else {
571
        $page_match = FALSE;
572
573
574
575
576
577
578
579
580
      }
    }
    else {
      $page_match = TRUE;
    }

  }
  return $page_match;
}
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595

/**
 * Based on headers send by clients this function returns TRUE if GA code should
 * be added to the current page and otherwise FALSE.
 */
function _googleanalytics_visibility_header($account) {

  if (($account->uid || variable_get('cache', 0) == 0) && variable_get('googleanalytics_privacy_donottrack', 1) && !empty($_SERVER['HTTP_DNT'])) {
    // Disable tracking if caching is disabled or a visitors is logged in and
    // have opted out from tracking via DNT (Do-Not-Track) header.
    return FALSE;
  }

  return TRUE;
}