forked from backdrop-contrib/matomo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matomo.module
766 lines (667 loc) · 27.6 KB
/
matomo.module
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
<?php
/**
* @file
* Drupal Module: Matomo
*
* Adds the required Javascript to all your Drupal pages to allow tracking by
* the Matomo statistics package.
*
* @author: Alexander Hass <https://drupal.org/user/85918>
*/
/**
* Define the default file extension list that should be tracked as download.
*/
define('MATOMO_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 https://drupal.org/node/34970 for more information.
*/
define('MATOMO_PAGES', "admin\nadmin/*\nbatch\nnode/add*\nnode/*/*\nuser/*/*");
/**
* Implements hook_theme().
*/
function matomo_theme() {
return array(
'matomo_admin_custom_var_table' => array(
'render element' => 'form',
),
);
}
/**
* Implements hook_permission().
*/
function matomo_permission() {
return array(
'administer matomo' => array(
'title' => t('Administer Matomo'),
'description' => t('Perform maintenance tasks for Matomo.'),
),
'opt-in or out of matomo 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 matomo tracking visibility' => array(
'title' => t('Use PHP for tracking visibility'),
'description' => t('Enter PHP code in the field for tracking visibility settings.'),
'restrict access' => TRUE,
),
'add js snippets for matomo' => array(
'title' => t('Add JavaScript snippets'),
'description' => 'Enter JavaScript code snippets for advanced Matomo functionality.',
'restrict access' => TRUE,
),
);
}
/**
* Implements hook_menu().
*/
function matomo_menu() {
$items['admin/config/system/matomo'] = array(
'title' => 'Matomo Analytics',
'description' => 'Configure the settings used to generate your Matomo tracking code.',
'page callback' => 'backdrop_get_form',
'page arguments' => array('matomo_admin_settings_form'),
'access arguments' => array('administer matomo'),
'type' => MENU_NORMAL_ITEM,
'file' => 'matomo.admin.inc',
);
return $items;
}
/**
* Implements hook_config_info().
*/
function matomo_config_info() {
$info['matomo.settings'] = array(
'label' => t('Matomo'),
'group' => t('Configuration'),
);
return $info;
}
/**
* Implements hook_preprocess_page().
*
* Insert JavaScript to the appropriate scope/region of the page, insert the
* noscript fallback to page_bottom if enabled.
*/
function matomo_preprocess_page(&$variables) {
global $user, $is_https;
$config = config('matomo.settings');
$id = $config->get('site_id');
// Get page status code for visibility filtering.
$status = backdrop_get_http_header('Status');
$trackable_status_codes = array(
'403 Forbidden',
'404 Not Found',
);
// 1. Check if the matomo 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 (preg_match('/^\d{1,}$/', $id) && (_matomo_visibility_pages() || in_array($status, $trackable_status_codes)) && _matomo_visibility_user($user)) {
$url_http = $config->get('url_http');
$url_https = $config->get('url_https');
$scope = $config->get('js_scope');
$set_custom_url = '';
$set_document_title = '';
// Add link tracking.
$link_settings = array();
$link_settings['trackMailto'] = $config->get('trackmailto');
if (module_exists('colorbox') && ($track_colorbox = $config->get('trackcolorbox'))) {
$link_settings['trackColorbox'] = $track_colorbox;
}
backdrop_add_js(array('matomo' => $link_settings), 'setting');
backdrop_add_js(backdrop_get_path('module', 'matomo') . '/matomo.js');
// Matomo can show a tree view of page titles that represents the site structure
// if setDocumentTitle() provides the page titles as a "/" delimited list.
// This may makes it easier to browse through the statistics of page titles
// on larger sites.
if ($config->get('page_title_hierarchy') == TRUE) {
$titles = _matomo_get_hierarchy_titles();
if ($config->get('page_title_hierarchy_exclude_home')) {
// Remove the "Home" item from the titles to flatten the tree view.
array_shift($titles);
}
// Remove all empty titles.
$titles = array_filter($titles);
if (!empty($titles)) {
// Encode title, at least to keep "/" intact.
$titles = array_map('rawurlencode', $titles);
$set_document_title = backdrop_json_encode(implode('/', $titles));
}
}
// Add messages tracking.
$message_events = '';
if ($message_types = $config->get('trackmessages')) {
$message_types = array_values(array_filter($message_types));
$status_heading = array(
'status' => t('Status message'),
'warning' => t('Warning message'),
'error' => t('Error message'),
);
foreach (backdrop_get_messages(NULL, FALSE) as $type => $messages) {
// Track only the selected message types.
if (in_array($type, $message_types)) {
foreach ($messages as $message) {
$message_events .= '_paq.push(["trackEvent", ' . backdrop_json_encode(t('Messages')) . ', ' . backdrop_json_encode($status_heading[$type]) . ', ' . backdrop_json_encode(strip_tags($message)) . ']);';
}
}
}
}
// If this node is a translation of another node, pass the original
// node instead.
if (module_exists('translation') && $config->get('translation_set')) {
// 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) && !empty($node->tnid) && ($node->tnid != $node->nid)) {
$source_node = node_load($node->tnid);
$languages = language_list();
$set_custom_url = backdrop_json_encode(url('node/' . $source_node->nid, array('language' => $languages[$source_node->language], 'absolute' => TRUE)));
}
}
// Track access denied (403) and file not found (404) pages.
if ($status == '403 Forbidden') {
$set_document_title = '"403/URL = " + encodeURIComponent(document.location.pathname+document.location.search) + "/From = " + encodeURIComponent(document.referrer)';
}
elseif ($status == '404 Not Found') {
$set_document_title = '"404/URL = " + encodeURIComponent(document.location.pathname+document.location.search) + "/From = " + encodeURIComponent(document.referrer)';
}
// #2693595: User has entered an invalid login and clicked on forgot
// password link. This link contains the username or email address and may
// get send to Matomo if we do not override it. Override only if 'name'
// query param exists. Last custom url condition, this need to win.
//
// URLs to protect are:
// - user/password?name=username
// - user/[email protected]
if (arg(0) == 'user' && arg(1) == 'password' && array_key_exists('name', backdrop_get_query_parameters())) {
$set_custom_url = backdrop_json_encode(url('user/password'));
}
// Add custom variables.
$matomo_custom_vars = $config->get('custom_var');
$custom_variable = '';
for ($i = 1; $i < 6; $i++) {
$custom_var_name = !empty($matomo_custom_vars['slots'][$i]['name']) ? $matomo_custom_vars['slots'][$i]['name'] : '';
if (!empty($custom_var_name)) {
$custom_var_value = !empty($matomo_custom_vars['slots'][$i]['value']) ? $matomo_custom_vars['slots'][$i]['value'] : '';
$custom_var_scope = !empty($matomo_custom_vars['slots'][$i]['scope']) ? $matomo_custom_vars['slots'][$i]['scope'] : 'visit';
$types = array();
$node = menu_get_object();
if (is_object($node)) {
$types += array('node' => $node);
}
$custom_var_name = token_replace($custom_var_name, $types, array('clear' => TRUE));
$custom_var_value = token_replace($custom_var_value, $types, array('clear' => TRUE));
// Suppress empty custom names and/or variables.
if (!backdrop_strlen(trim($custom_var_name)) || !backdrop_strlen(trim($custom_var_value))) {
continue;
}
// Custom variables names and values are limited to 200 characters in
// length. It is recommended to store values that are as small as
// possible to ensure that the Matomo Tracking request URL doesn't go
// over the URL limit for the webserver or browser.
$custom_var_name = rtrim(substr($custom_var_name, 0, 200));
$custom_var_value = rtrim(substr($custom_var_value, 0, 200));
$custom_var_name = backdrop_json_encode($custom_var_name);
$custom_var_value = backdrop_json_encode($custom_var_value);
$custom_var_scope = backdrop_json_encode($custom_var_scope);
$custom_variable .= "_paq.push(['setCustomVariable', $i, $custom_var_name, $custom_var_value, $custom_var_scope]);";
}
}
// Add any custom code snippets if specified.
$codesnippet_before = $config->get('codesnippet_before');
$codesnippet_after = $config->get('codesnippet_after');
// Build tracker code. See https://matomo.org/docs/javascript-tracking/#toc-asynchronous-tracking
$script = 'var _paq = _paq || [];';
$script .= '(function(){';
$script .= 'var u=(("https:" == document.location.protocol) ? "' . check_url($url_https) . '" : "' . check_url($url_http) . '");';
$script .= '_paq.push(["setSiteId", ' . backdrop_json_encode($config->get('site_id')) . ']);';
$script .= '_paq.push(["setTrackerUrl", u+"matomo.php"]);';
// Track logged in users across all devices.
if ($config->get('trackuserid') && 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.
$script .= '_paq.push(["setUserId", ' . backdrop_json_encode(matomo_user_id_hash($user->uid)) . ']);';
}
// Set custom url.
if (!empty($set_custom_url)) {
$script .= '_paq.push(["setCustomUrl", ' . $set_custom_url . ']);';
}
// Set custom document title.
if (!empty($set_document_title)) {
$script .= '_paq.push(["setDocumentTitle", ' . $set_document_title . ']);';
}
// Custom file download extensions.
if (($config->get('track')) && !($config->get('trackfiles_extensions') == MATOMO_TRACKFILES_EXTENSIONS)) {
$script .= '_paq.push(["setDownloadExtensions", ' . backdrop_json_encode($config->get('trackfiles_extensions')) . ']);';
}
// Disable tracking for visitors who have opted out from tracking via DNT (Do-Not-Track) header.
if ($config->get('privacy_donottrack')) {
$script .= '_paq.push(["setDoNotTrack", 1]);';
}
// Domain tracking type.
global $cookie_domain;
$domain_mode = $config->get('domain_mode');
// 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 .= '_paq.push(["setCookieDomain", ' . backdrop_json_encode($cookie_domain) . ']);';
}
// Ordering $custom_variable before $codesnippet_before allows users to add
// custom code snippets that may use deleteCustomVariable() and/or getCustomVariable().
if (!empty($custom_variable)) {
$script .= $custom_variable;
}
if (!empty($codesnippet_before)) {
$script .= $codesnippet_before;
}
// Site search tracking support.
// NOTE: It's recommended not to call trackPageView() on the Site Search Result page.
if (module_exists('search') && $config->get('site_search') && arg(0) == 'search' && $keys = matomo_search_get_keys()) {
// Parameters:
// 1. Search keyword searched for. Example: "Banana"
// 2. Search category selected in your search engine. If you do not need
// this, set to false. Example: "Organic Food"
// 3. Number of results on the Search results page. Zero indicates a
// 'No Result Search Keyword'. Set to false if you don't know.
//
// 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.
$script .= '_paq.push(["trackSiteSearch", ' . backdrop_json_encode($keys) . ', false, (window.matomo_search_results) ? window.matomo_search_results : 0]);';
}
else {
$script .= '_paq.push(["trackPageView"]);';
}
// Add link tracking.
if ($config->get('track')) {
// Disable tracking of links with ".no-tracking" and ".colorbox" classes.
$ignore_classes = array(
'no-tracking',
'colorbox',
);
// Disable the download & outlink tracking for specific CSS classes.
// Custom code snippets with 'setIgnoreClasses' will override the value.
// https://developer.matomo.org/api-reference/tracking-javascript#disable-the-download-amp-outlink-tracking-for-specific-css-classes
$script .= '_paq.push(["setIgnoreClasses", ' . backdrop_json_encode($ignore_classes) . ']);';
// Enable download & outlink link tracking.
$script .= '_paq.push(["enableLinkTracking"]);';
}
if (!empty($message_events)) {
$script .= $message_events;
}
if (!empty($codesnippet_after)) {
$script .= $codesnippet_after;
}
$script .= 'var d=document,';
$script .= 'g=d.createElement("script"),';
$script .= 's=d.getElementsByTagName("script")[0];';
$script .= 'g.type="text/javascript";';
$script .= 'g.defer=true;';
$script .= 'g.async=true;';
// Should a local cached copy of the tracking code be used?
if ($config->get('cache') && $url = _matomo_cache($url_http . 'matomo.js')) {
// 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 = '?' . state_get('css_js_query_string', '0');
$script .= 'g.src="' . $url . $query_string . '";';
}
else {
$script .= 'g.src=u+"matomo.js";';
}
$script .= 's.parentNode.insertBefore(g,s);';
$script .= '})();';
// Add tracker code to scope.
backdrop_add_js($script, array('scope' => $scope, 'type' => 'inline'));
// Add the noscript fallback markup to the page_bottom string.
if ($config->get('noscript')) {
$src_url = ($is_https && !empty($url_https)) ? check_url($url_https) : check_url($url_http);
$src_url = rtrim($src_url, '/') . "/matomo.php?idsite=$id&rec=1";
$img = '<img src="' . $src_url . '" style="border:0" alt="" />';
$variables['page_bottom'] .= "<!-- Matomo --><noscript><p>$img</p></noscript><!-- End Matomo -->";
}
}
}
/**
* Generate user id hash to implement USER_ID.
*
* 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.
*
* @param int $uid
* User id.
*
* @return string
* User id hash.
*/
function matomo_user_id_hash($uid) {
return backdrop_hmac_base64($uid, backdrop_get_private_key() . backdrop_get_hash_salt());
}
/**
* Implements hook_field_extra_fields().
*/
function matomo_field_extra_fields() {
$extra['user']['user']['form']['matomo'] = array(
'label' => t('Matomo configuration'),
'description' => t('Matomo module form element.'),
'weight' => 3,
);
return $extra;
}
/**
* Implement hook_form_FORM_ID_alter().
*
* Allow users to decide if tracking code will be added to pages or not.
*/
function matomo_form_user_profile_form_alter(&$form, &$form_state) {
$account = $form['#user'];
if (user_access('opt-in or out of matomo tracking') && ($custom = config_get('matomo.settings', 'custom')) != 0 && _matomo_visibility_roles($account)) {
$form['matomo'] = array(
'#type' => 'fieldset',
'#title' => t('Matomo 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;
}
// Migrate old piwik settings to matomo.
if (isset($account->data['piwik']['custom'])) {
$account->data['matomo']['custom'] = $account->data['piwik']['custom'];
}
$form['matomo']['custom'] = array(
'#type' => 'checkbox',
'#title' => t('Enable user tracking'),
'#description' => $description,
'#default_value' => isset($account->data['matomo']['custom']) ? $account->data['matomo']['custom'] : ($custom == 1),
);
return $form;
}
}
/**
* Implements hook_user_presave().
*/
function matomo_user_presave($account) {
if (isset($account->matomo['custom'])) {
$account->data['matomo']['custom'] = $account->matomo['custom'];
}
// Remove old piwik setting to complete migration to matomo.
if (isset($account->data['piwik'])) {
unset($account->data['piwik']);
}
}
/**
* Implements hook_cron().
*/
function matomo_cron() {
$config = config('matomo.settings');
// Regenerate the matomo.js every day.
if (REQUEST_TIME - $config->get('last_cache') >= 86400 && $config->get('cache', 0)) {
_matomo_cache($config->get('url_http', '') . 'matomo.js', TRUE);
$config->set('last_cache', REQUEST_TIME);
$config->save();
}
}
/**
* Implements hook_preprocess_search_results().
*
* Collects and adds the number of search results to the head.
*/
function matomo_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;
// But when there's no hit, that variable is NULL.
if (is_array($pager_total_items)) {
$num_results = (int) $pager_total_items[0];
}
else {
$num_results = 0;
}
backdrop_add_js('window.matomo_search_results = ' . $num_results . ';', array('type' => 'inline', 'group' => JS_LIBRARY-1));
}
/**
* 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 _matomo_cache($location, $sync_cached_file = FALSE) {
$path = 'public://matomo';
$file_destination = $path . '/' . basename($location);
if (!file_exists($file_destination) || $sync_cached_file) {
// Download the latest tracking code.
$result = backdrop_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 = backdrop_hash_base64(file_get_contents($file_destination));
$data_hash_remote = backdrop_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);
// Based on Drupal Core backdrop_build_css_cache().
if (config_get('system.core', 'preprocess_css') && config_get('system.core', 'clean_url') && extension_loaded('zlib')) {
file_unmanaged_save_data(gzencode($result->data, 9, FORCE_GZIP), $file_destination . '.gz', FILE_EXISTS_REPLACE);
}
watchdog('matomo', 'Locally cached tracking code file has been updated.', array(), WATCHDOG_INFO);
// Change query-strings on css/js files to enforce reload for all users.
_backdrop_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);
if (config_get('system.core', 'preprocess_css') && config_get('system.core', 'clean_url') && extension_loaded('zlib')) {
file_unmanaged_save_data(gzencode($result->data, 9, FORCE_GZIP), $file_destination . '.gz', FILE_EXISTS_REPLACE);
}
watchdog('matomo', '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 matomo_clear_js_cache() {
$path = 'public://matomo';
if (file_prepare_directory($path)) {
file_scan_directory($path, '/.*/', array('callback' => 'file_unmanaged_delete'));
backdrop_rmdir($path);
// Change query-strings on css/js files to enforce reload for all users.
_backdrop_flush_css_js();
watchdog('matomo', 'Local cache has been purged.', array(), WATCHDOG_INFO);
}
}
/**
* Helper function for grabbing search keys. Function is missing in D7.
*
* https://api.drupal.org/api/function/search_get_keys/6
*/
function matomo_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;
}
/**
* 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 Matomo.
*/
function _matomo_visibility_user($account) {
$enabled = FALSE;
// Is current user a member of a role that should be tracked?
if (_matomo_visibility_roles($account)) {
// Use the user's block visibility setting, if necessary.
if (($custom = config_get('matomo.settings', 'custom')) != 0) {
if ($account->uid && isset($account->data['matomo']['custom'])) {
$enabled = $account->data['matomo']['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 _matomo_visibility_roles($account) {
$visibility = config_get('matomo.settings', 'visibility_roles');
$enabled = $visibility;
$roles = array_filter(config_get('matomo.settings', 'roles'));
if (!empty($roles)) {
// One or more roles are selected.
foreach ($account->roles as $role) {
// Is the current user a member of one of these roles?
if (isset($roles[$role]) && $role == $roles[$role]) {
// 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 _matomo_visibility_pages() {
static $page_match;
// Cache visibility setting in hook_init for hook_footer.
if (!isset($page_match)) {
$visibility = config_get('matomo.settings', 'visibility_pages');
$setting_pages = config_get('matomo.settings', '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 = backdrop_strtolower($setting_pages);
if ($visibility < 2) {
// Convert the Drupal path to lowercase
$path = backdrop_strtolower(backdrop_get_path_alias($_GET['q']));
// Compare the lowercase internal and lowercase path alias (if any).
$page_match = backdrop_match_path($path, $pages);
if ($path != $_GET['q']) {
$page_match = $page_match || backdrop_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);
}
elseif (module_exists('php')) {
$page_match = php_eval($setting_pages);
}
else {
$page_match = FALSE;
}
}
else {
$page_match = TRUE;
}
}
return $page_match;
}
/**
* Get the page titles trail for the current page.
*
* Based on menu_get_active_breadcrumb().
*
* @return array
* All page titles, including current page.
*/
function _matomo_get_hierarchy_titles() {
$titles = array();
// No breadcrumb for the front page.
if (backdrop_is_front_page()) {
return $titles;
}
$item = menu_get_item();
if (!empty($item['access'])) {
$active_trail = menu_get_active_trail();
// Allow modules to alter the breadcrumb, if possible, as that is much
// faster than rebuilding an entirely new active trail.
backdrop_alter('menu_breadcrumb', $active_trail, $item);
// Remove the tab root (parent) if the current path links to its parent.
// Normally, the tab root link is included in the breadcrumb, as soon as we
// are on a local task or any other child link. However, if we are on a
// default local task (e.g., node/%/view), then we do not want the tab root
// link (e.g., node/%) to appear, as it would be identical to the current
// page. Since this behavior also needs to work recursively (i.e., on
// default local tasks of default local tasks), and since the last non-task
// link in the trail is used as page title (see menu_get_active_title()),
// this condition cannot be cleanly integrated into menu_get_active_trail().
// menu_get_active_trail() already skips all links that link to their parent
// (commonly MENU_DEFAULT_LOCAL_TASK). In order to also hide the parent link
// itself, we always remove the last link in the trail, if the current
// router item links to its parent.
if (($item['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT) {
array_pop($active_trail);
}
foreach ($active_trail as $parent) {
$titles[] = $parent['title'];
}
}
return $titles;
}
/**
* Helper function to verify that Backdrop can make http requests.
*
* @return bool
* TRUE if http response was received, FALSE otherwise.
*/
function _matomo_check_http_request() {
$works = &backdrop_static(__FUNCTION__);
if (!isset($works)) {
// Try to get the content of the front page.
$result = backdrop_http_request(url('', array('absolute' => TRUE)), array(
'max_redirects' => 0,
'timeout' => 10,
));
$works = isset($result->code) && ($result->code >= 100) && ($result->code < 600);
}
return $works;
}