-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgoogleanalytics.module
More file actions
706 lines (613 loc) · 26.9 KB
/
googleanalytics.module
File metadata and controls
706 lines (613 loc) · 26.9 KB
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
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
487
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
<?php
/**
* @file
* Drupal Module: Google Analytics
*
* Adds the required Javascript to all your Drupal pages to allow tracking by
* the Google Analytics statistics package.
*
* @author: Alexander Hass <http://drupal.org/user/85918>
*/
/**
* Define the default file extension list that should be tracked as download.
*/
define('GOOGLEANALYTICS_TRACKFILES_EXTENSIONS', '7z|aac|arc|arj|asf|asx|avi|bin|csv|doc(x|m)?|dot(x|m)?|exe|flv|gif|gz|gzip|hqx|jar|jpe?g|js|mp(2|3|4|e?g)|mov(ie)?|msi|msp|pdf|phps|png|ppt(x|m)?|pot(x|m)?|pps(x|m)?|ppam|sld(x|m)?|thmx|qtm?|ra(m|r)?|sea|sit|tar|tgz|torrent|txt|wav|wma|wmv|wpd|xls(x|m|b)?|xlt(x|m)|xlam|xml|z|zip');
/**
* Define default path exclusion list to remove tracking from admin pages,
* see http://drupal.org/node/34970 for more information.
*/
define('GOOGLEANALYTICS_PAGES', "admin\nadmin/*\nbatch\nnode/add*\nnode/*/*\nuser/*/*");
/**
* Advertise the supported google analytics api details.
*/
function googleanalytics_api() {
return array(
'api' => 'analytics.js',
);
}
/**
* Implementation of hook_help().
*/
function googleanalytics_help($path, $arg) {
switch ($path) {
case 'admin/settings/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/'));
}
}
/**
* Implementation of hook_theme().
*/
function googleanalytics_theme() {
return array(
'googleanalytics_admin_custom_var_table' => array(
'arguments' => array('form' => NULL),
),
);
}
/**
* Implementation of hook_theme_registry_alter().
*/
function googleanalytics_theme_registry_alter(&$registry) {
// Add custom preprocess function to the beginning of the stack.
// This allows use of the drupal_add_js() function before $vars is populated.
array_unshift($registry['page']['preprocess functions'], 'googleanalytics_add_js');
}
/**
* Implementation of hook_perm().
*/
function googleanalytics_perm() {
return array('administer google analytics', 'opt-in or out of tracking', 'use PHP for tracking visibility', 'add JS snippets for google analytics');
}
/**
* Implementation of hook_menu().
*/
function googleanalytics_menu() {
$items['admin/settings/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;
}
/**
* Adds Google Analytics tracking scripts.
*/
function googleanalytics_add_js(&$vars, $hook) {
global $user;
$id = variable_get('googleanalytics_account', '');
// Get page status code for visibility filtering.
$status = _googleanalytics_get_http_header('Status');
$trackable_status_codes = array(
'403 Forbidden',
'404 Not Found',
);
// 1. Check if the GA account number has a valid 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 (preg_match('/^UA-\d+-\d+$/', $id) && (_googleanalytics_visibility_pages() || in_array($status, $trackable_status_codes)) && _googleanalytics_visibility_user($user)) {
$debug = variable_get('googleanalytics_debug', 0);
$url_custom = '';
// Add link tracking.
$link_settings = array();
if ($track_outbound = variable_get('googleanalytics_trackoutgoing', 1)) {
$link_settings['trackOutbound'] = $track_outbound;
}
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', GOOGLEANALYTICS_TRACKFILES_EXTENSIONS))) {
$link_settings['trackDownload'] = $track_download;
$link_settings['trackDownloadExtensions'] = $trackfiles_extensions;
}
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', '')) {
$link_settings['trackCrossDomains'] = preg_split('/(\r\n?|\n)/', $track_cross_domains);
}
if ($track_url_fragments = variable_get('googleanalytics_trackurlfragments', 0)) {
$link_settings['trackUrlFragments'] = $track_url_fragments;
$url_custom = 'location.pathname + location.search + location.hash';
}
if (!empty($link_settings)) {
drupal_add_js(array('googleanalytics' => $link_settings), 'setting');
// Add debugging code.
if ($debug) {
drupal_add_js(drupal_get_path('module', 'googleanalytics') . '/googleanalytics.debug.js');
// Add the JS test in development to the page.
//drupal_add_js(drupal_get_path('module', 'googleanalytics') . '/googleanalytics.test.js');
}
else {
drupal_add_js(drupal_get_path('module', 'googleanalytics') . '/googleanalytics.js');
}
}
// Add messages tracking.
$message_events = '';
if ($message_types = variable_get('googleanalytics_trackmessages', array())) {
$message_types = array_values(array_filter($message_types));
$status_heading = array(
'status' => t('Status message'),
'warning' => t('Warning message'),
'error' => t('Error message'),
);
foreach (drupal_get_messages(NULL, FALSE) as $type => $messages) {
// Track only the selected message types.
if (in_array($type, $message_types)) {
foreach ($messages as $message) {
// @todo: Track as exceptions?
$message_events .= 'ga("send", "event", ' . drupal_to_js(t('Messages')) . ', ' . drupal_to_js($status_heading[$type]) . ', ' . drupal_to_js(strip_tags($message)) . ');';
}
}
}
}
// Site search tracking support.
if (module_exists('search') && variable_get('googleanalytics_site_search', FALSE) && arg(0) == 'search' && $keys = search_get_keys()) {
// hook_preprocess_search_results() is not executed if search result is
// empty. Make sure the counter is set to 0 if there are no results.
$url_custom = '(window.googleanalytics_search_results) ? ' . drupal_to_js(url('search/'. arg(1), array('query' => 'search='. drupal_urlencode($keys)))) . ' : ' . drupal_to_js(url('search/'. arg(1), array('query' => 'search=no-results:'. drupal_urlencode($keys) .'&cat=no-results')));
}
// 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 ($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 custom dimensions and metrics.
$custom_var = '';
foreach (array('dimension', 'metric') as $googleanalytics_custom_type) {
$googleanalytics_custom_vars = variable_get('googleanalytics_custom_' . $googleanalytics_custom_type, array());
// Are there dimensions or metrics configured?
if (!empty($googleanalytics_custom_vars)) {
// Add all the configured variables to the content.
foreach ($googleanalytics_custom_vars as $googleanalytics_custom_var) {
if (module_exists('token')) {
$types = array('global' => NULL, 'user' => $user);
$node = menu_get_object();
if (is_object($node)) {
$types += array('node' => $node);
}
$googleanalytics_custom_var['value'] = token_replace_multiple($googleanalytics_custom_var['value'], $types, '[', ']', array('clear' => TRUE));
}
// Suppress empty custom names and/or variables.
if (!drupal_strlen(trim($googleanalytics_custom_var['value']))) {
continue;
}
// Per documentation the max length of a dimension is 150 bytes.
// A metric has no length limitation. It's not documented if this
// limit means 150 bytes after url encoding or before.
// See https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#customs
if ($googleanalytics_custom_type == 'dimension' && drupal_strlen($googleanalytics_custom_var['value']) > 150) {
$googleanalytics_custom_var['value'] = substr($googleanalytics_custom_var['value'], 0, 150);
}
// Cast metric values for json_encode to data type numeric.
if ($googleanalytics_custom_type == 'metric') {
settype($googleanalytics_custom_var['value'], 'float');
};
$custom_var .= 'ga("set", ' . drupal_to_js($googleanalytics_custom_type . $googleanalytics_custom_var['index']) . ', ' . drupal_to_js($googleanalytics_custom_var['value']) . ');';
}
}
}
// Build tracker code.
$script = '(function(i,s,o,g,r,a,m){';
$script .= 'i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){';
$script .= '(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),';
$script .= 'm=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)';
$script .= '})(window,document,"script",';
// Which version of the tracking library should be used?
$library_tracker_url = '//www.google-analytics.com/' . ($debug ? 'analytics_debug.js' : 'analytics.js');
$library_cache_url = 'http:' . $library_tracker_url;
// Should a local cached copy of analytics.js be used?
if (variable_get('googleanalytics_cache', 0) && $url = _googleanalytics_cache($library_cache_url)) {
// 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 = '?' . substr(variable_get('css_js_query_string', '0'), 0, 1);
$script .= '"' . $url . $query_string . '"';
}
else {
$script .= '"' . $library_tracker_url . '"';
}
$script .= ',"ga");';
// Add any custom code snippets if specified.
$codesnippet_create = variable_get('googleanalytics_codesnippet_create', array());
$codesnippet_before = variable_get('googleanalytics_codesnippet_before', '');
$codesnippet_after = variable_get('googleanalytics_codesnippet_after', '');
// Build the create only fields list.
$create_only_fields = array('cookieDomain' => 'auto');
$create_only_fields = array_merge($create_only_fields, $codesnippet_create);
// Domain tracking type.
global $cookie_domain;
$domain_mode = variable_get('googleanalytics_domain_mode', 0);
$googleanalytics_adsense_script = '';
// 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))) {
$create_only_fields = array_merge($create_only_fields, array('cookieDomain' => $cookie_domain));
$googleanalytics_adsense_script .= 'window.google_analytics_domain_name = ' . drupal_to_js($cookie_domain) . ';';
}
elseif ($domain_mode == 2) {
// Cross Domain tracking. 'autoLinker' need to be enabled in 'create'.
$create_only_fields = array_merge($create_only_fields, array('allowLinker' => TRUE));
$googleanalytics_adsense_script .= 'window.google_analytics_domain_name = "none";';
}
// Track logged in users across all devices.
if (variable_get('googleanalytics_trackuserid', 0) && user_is_logged_in()) {
// The USER_ID value should be a unique, persistent, and non-personally
// identifiable string identifier that represents a user or signed-in
// account across devices.
$create_only_fields['userId'] = _googleanalytics_hmac_base64($user->uid, drupal_get_private_key() . _googleanalytics_get_hash_salt());
}
// Create a tracker.
$script .= 'ga("create", ' . drupal_to_js($id) . ', ' . drupal_to_js($create_only_fields) .');';
// Prepare Adsense tracking.
$googleanalytics_adsense_script .= 'window.google_analytics_uacct = ' . drupal_to_js($id) . ';';
// Add enhanced link attribution after 'create', but before 'pageview' send.
// @see https://support.google.com/analytics/answer/2558867
if (variable_get('googleanalytics_tracklinkid', 0)) {
$script .= 'ga("require", "linkid", "linkid.js");';
}
// Add display features after 'create', but before 'pageview' send.
// @see https://support.google.com/analytics/answer/2444872
if (variable_get('googleanalytics_trackdoubleclick', 0)) {
$script .= 'ga("require", "displayfeatures");';
}
// Domain tracking type.
if ($domain_mode == 2) {
// Cross Domain tracking
// https://developers.google.com/analytics/devguides/collection/upgrade/reference/gajs-analyticsjs#cross-domain
$script .= 'ga("require", "linker");';
$script .= 'ga("linker:autoLink", ' . drupal_to_js($link_settings['trackCrossDomains']) . ');';
}
if (variable_get('googleanalytics_tracker_anonymizeip', 1)) {
$script .= 'ga("set", "anonymizeIp", true);';
}
if (!empty($custom_var)) {
$script .= $custom_var;
}
if (!empty($codesnippet_before)) {
$script .= $codesnippet_before;
}
if (!empty($url_custom)) {
$script .= 'ga("set", "page", ' . $url_custom . ');';
}
$script .= 'ga("send", "pageview");';
if (!empty($message_events)) {
$script .= $message_events;
}
if (!empty($codesnippet_after)) {
$script .= $codesnippet_after;
}
if (variable_get('googleanalytics_trackadsense', FALSE)) {
// Custom tracking. Prepend before all other JavaScript.
// @TODO: https://support.google.com/adsense/answer/98142
// sounds like it could be appended to $script.
drupal_add_js($googleanalytics_adsense_script, 'inline', 'header');
}
drupal_add_js($script, 'inline', 'header');
}
}
/**
* Implementation of hook_user().
*
* Allow users to decide if tracking code will be added to pages or not.
*/
function googleanalytics_user($type, $edit, &$account, $category = NULL) {
switch ($type) {
case 'form':
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;
}
// 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->googleanalytics['custom'] = FALSE;
$description .= '<span class="admin-disabled">';
$description .= ' ' . t('You have opted out from tracking via browser privacy settings.');
$description .= '</span>';
}
$form['googleanalytics']['custom'] = array(
'#type' => 'checkbox',
'#title' => t('Enable user tracking'),
'#description' => $description,
'#default_value' => isset($account->googleanalytics['custom']) ? $account->googleanalytics['custom'] : ($custom == 1),
'#disabled' => $disabled,
);
return $form;
}
break;
}
}
/**
* Implementation of hook_cron().
*/
function googleanalytics_cron() {
// Regenerate the tracking code file every day.
// Regenerate the tracking code file every day.
if (time() - variable_get('googleanalytics_last_cache', 0) >= 86400 && variable_get('googleanalytics_cache', 0)) {
_googleanalytics_cache('http://www.google-analytics.com/analytics.js', TRUE);
variable_set('googleanalytics_last_cache', time());
}
}
/**
* Implementation of hook_preprocess_search_results().
*
* Collects the number of search results. It need to be noted, that this
* function is not executed if the search result is empty.
*/
function googleanalytics_preprocess_search_results(&$variables) {
if (variable_get('googleanalytics_site_search', FALSE)) {
// 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]) . ';', 'inline', 'header');
}
}
/**
* Download/Synchronize/Cache tracking code file locally.
*
* @param $location
* The full URL to the external javascript file.
* @param $synchronize
* Synchronize to local cache if remote file has changed.
* @return mixed
* The path to the local javascript file on success, boolean FALSE on failure.
*/
function _googleanalytics_cache($location, $synchronize = FALSE) {
$path = file_create_path('googleanalytics');
$file_destination = $path . '/' . basename($location);
if (!file_exists($file_destination) || $synchronize) {
// 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 = md5(file_get_contents($file_destination));
$data_hash_remote = md5($result->data);
// Check that the files directory is writable.
if ($data_hash_local != $data_hash_remote && file_check_directory($path)) {
// Save updated tracking code file to disk.
file_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_check_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_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 base_path() . $file_destination;
}
}
}
}
else {
// Return the local JS file path.
return base_path() . $file_destination;
}
}
/**
* Delete cached files and directory.
*/
function googleanalytics_clear_js_cache() {
$path = file_create_path('googleanalytics');
if (file_check_directory($path)) {
file_scan_directory($path, '.*', array('.', '..', 'CVS'), 'file_delete', TRUE);
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?
if (_googleanalytics_visibility_header($account) && _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) {
$visibility = variable_get('googleanalytics_visibility_roles', 0);
$enabled = $visibility;
$roles = variable_get('googleanalytics_roles', array());
if (array_sum($roles) > 0) {
// One or more roles are selected.
foreach (array_keys($account->roles) as $rid) {
// Is the current user a member of one of these roles?
if (isset($roles[$rid]) && $rid == $roles[$rid]) {
// Current user is a member of a role that should be tracked/excluded from tracking.
$enabled = !$visibility;
break;
}
}
}
else {
// No role is selected for tracking, therefore 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 googleanalytics_add_js.
if (!isset($page_match)) {
$visibility = variable_get('googleanalytics_visibility', 0);
$setting_pages = variable_get('googleanalytics_pages', GOOGLEANALYTICS_PAGES);
// Match path if necessary.
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);
if ($visibility < 2) {
// 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).
$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 tracking code 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($setting_pages);
}
}
else {
$page_match = TRUE;
}
}
return $page_match;
}
/**
* 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;
}
/**
* Backport of https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal_get_hash_salt/7
*
* Gets a salt useful for hardening against SQL injection.
*/
function _googleanalytics_get_hash_salt() {
global $drupal_hash_salt, $db_url;
// If the $drupal_hash_salt variable is empty, a hash of the serialized
// database credentials is used as a fallback salt.
return empty($drupal_hash_salt) ? hash('sha256', $db_url) : $drupal_hash_salt;
}
/**
* Backport of https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal_hmac_base64/7
*
* Calculates a base-64 encoded, URL-safe sha-256 hmac.
*/
function _googleanalytics_hmac_base64($data, $key) {
// Casting $data and $key to strings here is necessary to avoid empty string
// results of the hash function if they are not scalar values. As this
// function is used in security-critical contexts like token validation it is
// important that it never returns an empty string.
$hmac = base64_encode(hash_hmac('sha256', (string) $data, (string) $key, TRUE));
// Modify the hmac so it's safe to use in URLs.
return strtr($hmac, array('+' => '-', '/' => '_', '=' => ''));
}
/**
* Emulate D7 drupal_get_http_header(). Looks a bit overkill.
*/
function _googleanalytics_get_http_header($name = NULL) {
$data = drupal_get_headers();
$raw_headers = preg_split('/(\r\n?|\n)/', $data);
$headers = array();
foreach ($raw_headers as $raw_header) {
// Header: HTTP/1.1 404 Not Found
if (preg_match('/^(HTTP\/\d.\d+)\s(\w+)/', $raw_header)) {
$status = preg_replace('/^(HTTP\/\d.\d+)\s/', '', $raw_header);
$headers['Status'] = $status;
continue;
}
list($header, $value) = explode(':', $raw_header);
$headers[trim($header)] = trim($value);
}
if (isset($name)) {
return isset($headers[$name]) ? $headers[$name] : NULL;
}
else {
return $headers;
}
}
/**
* Implementation of hook_token_list().
*/
function googleanalytics_token_list($type = 'all') {
if ($type == 'user' || $type == 'all') {
$tokens['user']['user-role-names'] = t('The role names the user account is a member of as comma separated list.');
$tokens['user']['user-role-ids'] = t('The role ids the user account is a member of as comma separated list.');
return $tokens;
}
}
/**
* Implementation of hook_token_values().
*/
function googleanalytics_token_values($type, $object = NULL, $options = array()) {
if ($type == 'user' && !empty($object->roles)) {
$account = $object;
// Basic user account information.
$tokens['user-role-names'] = implode(',', $account->roles);
$tokens['user-role-ids'] = implode(',', array_keys($account->roles));
return $tokens;
}
}