Projet

Général

Profil

Paste
Télécharger (26,9 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / matomo / matomo.module @ 60283730

1
<?php
2

    
3
/**
4
 * @file
5
 * Drupal Module: Matomo
6
 *
7
 * Adds the required Javascript to all your Drupal pages to allow tracking by
8
 * the Matomo statistics package.
9
 *
10
 * @author: Alexander Hass <http://drupal.org/user/85918>
11
 */
12

    
13
/**
14
 * Define the default file extension list that should be tracked as download.
15
 */
16
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');
17

    
18
/**
19
 * Define default path exclusion list to remove tracking from admin pages,
20
 * see http://drupal.org/node/34970 for more information.
21
 */
22
define('MATOMO_PAGES', "admin\nadmin/*\nbatch\nnode/add*\nnode/*/*\nuser/*/*");
23

    
24
/**
25
 * Implements hook_help().
26
 */
27
function matomo_help($path, $arg) {
28
  switch ($path) {
29
    case 'admin/config/system/matomo':
30
      return t('<a href="@pk_url">Matomo Analytics</a> is an open source (GPL license) web analytics software. It gives interesting reports on your website visitors, your popular pages, the search engines keywords they used, the language they speak... and so much more. Matomo aims to be an open source alternative to Google Analytics.', array('@pk_url' => 'http://www.matomo.org/'));
31
  }
32
}
33

    
34
/**
35
 * Implements hook_theme().
36
 */
37
function matomo_theme() {
38
  return array(
39
    'matomo_admin_custom_var_table' => array(
40
      'render element' => 'form',
41
    ),
42
  );
43
}
44

    
45
/**
46
 * Implements hook_permission().
47
 */
48
function matomo_permission() {
49
  return array(
50
    'administer matomo' => array(
51
      'title' => t('Administer Matomo'),
52
      'description' => t('Perform maintenance tasks for Matomo.'),
53
    ),
54
    'opt-in or out of matomo tracking' => array(
55
      'title' => t('Opt-in or out of tracking'),
56
      'description' => t('Allow users to decide if tracking code will be added to pages or not.'),
57
    ),
58
    'use php for matomo tracking visibility' => array(
59
      'title' => t('Use PHP for tracking visibility'),
60
      'description' => t('Enter PHP code in the field for tracking visibility settings.'),
61
      'restrict access' => TRUE,
62
    ),
63
    'add js snippets for matomo' => array(
64
      'title' => t('Add JavaScript snippets'),
65
      'description' => 'Enter JavaScript code snippets for advanced Matomo functionality.',
66
      'restrict access' => TRUE,
67
    ),
68
  );
69
}
70

    
71
/**
72
 * Implements hook_menu().
73
 */
74
function matomo_menu() {
75
  $items['admin/config/system/matomo'] = array(
76
    'title' => 'Matomo Analytics',
77
    'description' => 'Configure the settings used to generate your Matomo tracking code.',
78
    'page callback' => 'drupal_get_form',
79
    'page arguments' => array('matomo_admin_settings_form'),
80
    'access arguments' => array('administer matomo'),
81
    'type' => MENU_NORMAL_ITEM,
82
    'file' => 'matomo.admin.inc',
83
  );
84

    
85
  return $items;
86
}
87

    
88
/**
89
 * Implements hook_page_alter() to insert JavaScript to the appropriate scope/region of the page.
90
 */
91
function matomo_page_alter(&$page) {
92
  global $user;
93

    
94
  $id = variable_get('matomo_site_id', '');
95

    
96
  // Get page status code for visibility filtering.
97
  $status = drupal_get_http_header('Status');
98
  $trackable_status_codes = array(
99
    '403 Forbidden',
100
    '404 Not Found',
101
  );
102

    
103
  // 1. Check if the matomo account number has a value.
104
  // 2. Track page views based on visibility value.
105
  // 3. Check if we should track the currently active user's role.
106
  if (preg_match('/^\d{1,}$/', $id) && (_matomo_visibility_pages() || in_array($status, $trackable_status_codes)) && _matomo_visibility_user($user)) {
107

    
108
    $url_http = variable_get('matomo_url_http', '');
109
    $url_https = variable_get('matomo_url_https', '');
110
    $scope = variable_get('matomo_js_scope', 'header');
111

    
112
    $set_custom_url = '';
113
    $set_document_title = '';
114

    
115
    // Add link tracking.
116
    $link_settings = array();
117
    $link_settings['trackMailto'] = variable_get('matomo_trackmailto', 1);
118

    
119
    if (module_exists('colorbox') && ($track_colorbox = variable_get('matomo_trackcolorbox', 1))) {
120
      $link_settings['trackColorbox'] = $track_colorbox;
121
    }
122

    
123
    drupal_add_js(array('matomo' => $link_settings), 'setting');
124
    drupal_add_js(drupal_get_path('module', 'matomo') . '/matomo.js');
125

    
126
    // Matomo can show a tree view of page titles that represents the site structure
127
    // if setDocumentTitle() provides the page titles as a "/" delimited list.
128
    // This may makes it easier to browse through the statistics of page titles
129
    // on larger sites.
130
    if (variable_get('matomo_page_title_hierarchy', FALSE) == TRUE) {
131
      $titles = _matomo_get_hierarchy_titles();
132

    
133
      if (variable_get('matomo_page_title_hierarchy_exclude_home', TRUE)) {
134
        // Remove the "Home" item from the titles to flatten the tree view.
135
        array_shift($titles);
136
      }
137

    
138
      // Remove all empty titles.
139
      $titles = array_filter($titles);
140

    
141
      if (!empty($titles)) {
142
        // Encode title, at least to keep "/" intact.
143
        $titles = array_map('rawurlencode', $titles);
144

    
145
        $set_document_title = drupal_json_encode(implode('/', $titles));
146
      }
147
    }
148

    
149
    // Add messages tracking.
150
    $message_events = '';
151
    if ($message_types = variable_get('matomo_trackmessages', array())) {
152
      $message_types = array_values(array_filter($message_types));
153
      $status_heading = array(
154
        'status' => t('Status message'),
155
        'warning' => t('Warning message'),
156
        'error' => t('Error message'),
157
      );
158

    
159
      foreach (drupal_get_messages(NULL, FALSE) as $type => $messages) {
160
        // Track only the selected message types.
161
        if (in_array($type, $message_types)) {
162
          foreach ($messages as $message) {
163
            $message_events .= '_paq.push(["trackEvent", ' . drupal_json_encode(t('Messages')) . ', ' . drupal_json_encode($status_heading[$type]) . ', ' . drupal_json_encode(strip_tags($message)) . ']);';
164
          }
165
        }
166
      }
167
    }
168

    
169
    // If this node is a translation of another node, pass the original
170
    // node instead.
171
    if (module_exists('translation') && variable_get('matomo_translation_set', 0)) {
172
      // Check we have a node object, it supports translation, and its
173
      // translated node ID (tnid) doesn't match its own node ID.
174
      $node = menu_get_object();
175
      if ($node && translation_supported_type($node->type) && !empty($node->tnid) && ($node->tnid != $node->nid)) {
176
        $source_node = node_load($node->tnid);
177
        $languages = language_list();
178
        $set_custom_url = drupal_json_encode(url('node/' . $source_node->nid, array('language' => $languages[$source_node->language], 'absolute' => TRUE)));
179
      }
180
    }
181

    
182
    // Track access denied (403) and file not found (404) pages.
183
    if ($status == '403 Forbidden') {
184
      $set_document_title = '"403/URL = " + encodeURIComponent(document.location.pathname+document.location.search) + "/From = " + encodeURIComponent(document.referrer)';
185
    }
186
    elseif ($status == '404 Not Found') {
187
      $set_document_title = '"404/URL = " + encodeURIComponent(document.location.pathname+document.location.search) + "/From = " + encodeURIComponent(document.referrer)';
188
    }
189

    
190
    // #2693595: User has entered an invalid login and clicked on forgot
191
    // password link. This link contains the username or email address and may
192
    // get send to Matomo if we do not override it. Override only if 'name'
193
    // query param exists. Last custom url condition, this need to win.
194
    //
195
    // URLs to protect are:
196
    // - user/password?name=username
197
    // - user/password?name=foo@example.com
198
    if (arg(0) == 'user' && arg(1) == 'password' && array_key_exists('name', drupal_get_query_parameters())) {
199
      $set_custom_url = drupal_json_encode(url('user/password'));
200
    }
201

    
202
    // Add custom variables.
203
    $matomo_custom_vars = variable_get('matomo_custom_var', array());
204
    $custom_variable = '';
205
    for ($i = 1; $i < 6; $i++) {
206
      $custom_var_name = !empty($matomo_custom_vars['slots'][$i]['name']) ? $matomo_custom_vars['slots'][$i]['name'] : '';
207
      if (!empty($custom_var_name)) {
208
        $custom_var_value = !empty($matomo_custom_vars['slots'][$i]['value']) ? $matomo_custom_vars['slots'][$i]['value'] : '';
209
        $custom_var_scope = !empty($matomo_custom_vars['slots'][$i]['scope']) ? $matomo_custom_vars['slots'][$i]['scope'] : 'visit';
210

    
211
        $types = array();
212
        $node = menu_get_object();
213
        if (is_object($node)) {
214
          $types += array('node' => $node);
215
        }
216
        $custom_var_name = token_replace($custom_var_name, $types, array('clear' => TRUE));
217
        $custom_var_value = token_replace($custom_var_value, $types, array('clear' => TRUE));
218

    
219
        // Suppress empty custom names and/or variables.
220
        if (!drupal_strlen(trim($custom_var_name)) || !drupal_strlen(trim($custom_var_value))) {
221
          continue;
222
        }
223

    
224
        // Custom variables names and values are limited to 200 characters in
225
        // length. It is recommended to store values that are as small as
226
        // possible to ensure that the Matomo Tracking request URL doesn't go
227
        // over the URL limit for the webserver or browser.
228
        $custom_var_name = rtrim(substr($custom_var_name, 0, 200));
229
        $custom_var_value = rtrim(substr($custom_var_value, 0, 200));
230

    
231
        $custom_var_name = drupal_json_encode($custom_var_name);
232
        $custom_var_value = drupal_json_encode($custom_var_value);
233
        $custom_var_scope = drupal_json_encode($custom_var_scope);
234
        $custom_variable .= "_paq.push(['setCustomVariable', $i, $custom_var_name, $custom_var_value, $custom_var_scope]);";
235
      }
236
    }
237

    
238
    // Add any custom code snippets if specified.
239
    $codesnippet_before = variable_get('matomo_codesnippet_before', '');
240
    $codesnippet_after = variable_get('matomo_codesnippet_after', '');
241

    
242
    // Build tracker code. See http://matomo.org/docs/javascript-tracking/#toc-asynchronous-tracking
243
    $script = 'var _paq = _paq || [];';
244
    $script .= '(function(){';
245
    $script .= 'var u=(("https:" == document.location.protocol) ? "' . check_url($url_https) . '" : "' . check_url($url_http) . '");';
246
    $script .= '_paq.push(["setSiteId", ' . drupal_json_encode(variable_get('matomo_site_id', '')) . ']);';
247
    $script .= '_paq.push(["setTrackerUrl", u+"piwik.php"]);';
248

    
249
    // Track logged in users across all devices.
250
    if (variable_get('matomo_trackuserid', 0) && user_is_logged_in()) {
251
      // The USER_ID value should be a unique, persistent, and non-personally
252
      // identifiable string identifier that represents a user or signed-in
253
      // account across devices.
254
      $script .= '_paq.push(["setUserId", ' . drupal_json_encode(matomo_user_id_hash($user->uid)) . ']);';
255
    }
256

    
257
    // Set custom url.
258
    if (!empty($set_custom_url)) {
259
      $script .= '_paq.push(["setCustomUrl", ' . $set_custom_url . ']);';
260
    }
261
    // Set custom document title.
262
    if (!empty($set_document_title)) {
263
      $script .= '_paq.push(["setDocumentTitle", ' . $set_document_title . ']);';
264
    }
265

    
266
    // Custom file download extensions.
267
    if ((variable_get('matomo_track', 1)) && !(variable_get('matomo_trackfiles_extensions', MATOMO_TRACKFILES_EXTENSIONS) == MATOMO_TRACKFILES_EXTENSIONS)) {
268
      $script .= '_paq.push(["setDownloadExtensions", ' . drupal_json_encode(variable_get('matomo_trackfiles_extensions', MATOMO_TRACKFILES_EXTENSIONS)) . ']);';
269
    }
270

    
271
    // Disable tracking for visitors who have opted out from tracking via DNT (Do-Not-Track) header.
272
    if (variable_get('matomo_privacy_donottrack', 1)) {
273
      $script .= '_paq.push(["setDoNotTrack", 1]);';
274
    }
275

    
276
    // Domain tracking type.
277
    global $cookie_domain;
278
    $domain_mode = variable_get('matomo_domain_mode', 0);
279

    
280
    // Per RFC 2109, cookie domains must contain at least one dot other than the
281
    // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
282
    if ($domain_mode == 1 && count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
283
      $script .= '_paq.push(["setCookieDomain", ' . drupal_json_encode($cookie_domain) . ']);';
284
    }
285

    
286
    // Ordering $custom_variable before $codesnippet_before allows users to add
287
    // custom code snippets that may use deleteCustomVariable() and/or getCustomVariable().
288
    if (!empty($custom_variable)) {
289
      $script .= $custom_variable;
290
    }
291
    if (!empty($codesnippet_before)) {
292
      $script .= $codesnippet_before;
293
    }
294

    
295
    // Site search tracking support.
296
    // NOTE: It's recommended not to call trackPageView() on the Site Search Result page.
297
    if (module_exists('search') && variable_get('matomo_site_search', FALSE) && arg(0) == 'search' && $keys = matomo_search_get_keys()) {
298
      // Parameters:
299
      // 1. Search keyword searched for. Example: "Banana"
300
      // 2. Search category selected in your search engine. If you do not need
301
      //    this, set to false. Example: "Organic Food"
302
      // 3. Number of results on the Search results page. Zero indicates a
303
      //    'No Result Search Keyword'. Set to false if you don't know.
304
      //
305
      // hook_preprocess_search_results() is not executed if search result is
306
      // empty. Make sure the counter is set to 0 if there are no results.
307
      $script .= '_paq.push(["trackSiteSearch", ' . drupal_json_encode($keys) . ', false, (window.matomo_search_results) ? window.matomo_search_results : 0]);';
308
    }
309
    else {
310
      $script .= '_paq.push(["trackPageView"]);';
311
    }
312

    
313
    // Add link tracking.
314
    if (variable_get('matomo_track', 1)) {
315
      // Disable tracking of links with ".no-tracking" and ".colorbox" classes.
316
      $ignore_classes = array(
317
        'no-tracking',
318
        'colorbox',
319
      );
320
      // Disable the download & outlink tracking for specific CSS classes.
321
      // Custom code snippets with 'setIgnoreClasses' will override the value.
322
      // http://developer.matomo.org/api-reference/tracking-javascript#disable-the-download-amp-outlink-tracking-for-specific-css-classes
323
      $script .= '_paq.push(["setIgnoreClasses", ' . drupal_json_encode($ignore_classes) . ']);';
324

    
325
      // Enable download & outlink link tracking.
326
      $script .= '_paq.push(["enableLinkTracking"]);';
327
    }
328

    
329
    if (!empty($message_events)) {
330
      $script .= $message_events;
331
    }
332
    if (!empty($codesnippet_after)) {
333
      $script .= $codesnippet_after;
334
    }
335

    
336
    $script .= 'var d=document,';
337
    $script .= 'g=d.createElement("script"),';
338
    $script .= 's=d.getElementsByTagName("script")[0];';
339
    $script .= 'g.type="text/javascript";';
340
    $script .= 'g.defer=true;';
341
    $script .= 'g.async=true;';
342

    
343
    // Should a local cached copy of the tracking code be used?
344
    if (variable_get('matomo_cache', 0) && $url = _matomo_cache($url_http . 'piwik.js')) {
345
      // A dummy query-string is added to filenames, to gain control over
346
      // browser-caching. The string changes on every update or full cache
347
      // flush, forcing browsers to load a new copy of the files, as the
348
      // URL changed.
349
      $query_string = '?' . variable_get('css_js_query_string', '0');
350

    
351
      $script .= 'g.src="' . $url . $query_string . '";';
352
    }
353
    else {
354
      $script .= 'g.src=u+"piwik.js";';
355
    }
356

    
357
    $script .= 's.parentNode.insertBefore(g,s);';
358
    $script .= '})();';
359

    
360
    // Add tracker code to scope.
361
    drupal_add_js($script, array('scope' => $scope, 'type' => 'inline'));
362
  }
363
}
364

    
365
/**
366
 * Generate user id hash to implement USER_ID.
367
 *
368
 * The USER_ID value should be a unique, persistent, and non-personally
369
 * identifiable string identifier that represents a user or signed-in
370
 * account across devices.
371
 *
372
 * @param int $uid
373
 *   User id.
374
 *
375
 * @return string
376
 *   User id hash.
377
 */
378
function matomo_user_id_hash($uid) {
379
  return drupal_hmac_base64($uid, drupal_get_private_key() . drupal_get_hash_salt());
380
}
381

    
382
/**
383
 * Implements hook_field_extra_fields().
384
 */
385
function matomo_field_extra_fields() {
386
  $extra['user']['user']['form']['matomo'] = array(
387
    'label' => t('Matomo configuration'),
388
    'description' => t('Matomo module form element.'),
389
    'weight' => 3,
390
  );
391

    
392
  return $extra;
393
}
394

    
395
/**
396
 * Implement hook_form_FORM_ID_alter().
397
 *
398
 * Allow users to decide if tracking code will be added to pages or not.
399
 */
400
function matomo_form_user_profile_form_alter(&$form, &$form_state) {
401
  $account = $form['#user'];
402
  $category = $form['#user_category'];
403

    
404
  if ($category == 'account' && user_access('opt-in or out of matomo tracking') && ($custom = variable_get('matomo_custom', 1)) != 0 && _matomo_visibility_roles($account)) {
405
    $form['matomo'] = array(
406
      '#type' => 'fieldset',
407
      '#title' => t('Matomo configuration'),
408
      '#weight' => 3,
409
      '#collapsible' => TRUE,
410
      '#tree' => TRUE
411
    );
412

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

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

    
423
    // Migrate old piwik settings to matomo.
424
    if (isset($account->data['piwik']['custom'])) {
425
      $account->data['matomo']['custom'] = $account->data['piwik']['custom'];
426
    }
427

    
428
    $form['matomo']['custom'] = array(
429
      '#type' => 'checkbox',
430
      '#title' => t('Enable user tracking'),
431
      '#description' => $description,
432
      '#default_value' => isset($account->data['matomo']['custom']) ? $account->data['matomo']['custom'] : ($custom == 1),
433
    );
434

    
435
    return $form;
436
  }
437
}
438

    
439
/**
440
 * Implements hook_user_presave().
441
 */
442
function matomo_user_presave(&$edit, $account, $category) {
443
  if (isset($edit['matomo']['custom'])) {
444
    $edit['data']['matomo']['custom'] = $edit['matomo']['custom'];
445
  }
446

    
447
  // Remove old piwik setting to complete migration to matomo.
448
  if (isset($edit['data']['piwik'])) {
449
    unset($edit['data']['piwik']);
450
  }
451
}
452

    
453
/**
454
 * Implements hook_cron().
455
 */
456
function matomo_cron() {
457
  // Regenerate the piwik.js every day.
458
  if (REQUEST_TIME - variable_get('matomo_last_cache', 0) >= 86400 && variable_get('matomo_cache', 0)) {
459
    _matomo_cache(variable_get('matomo_url_http', '') . 'piwik.js', TRUE);
460
    variable_set('matomo_last_cache', REQUEST_TIME);
461
  }
462
}
463

    
464
/**
465
 * Implements hook_preprocess_search_results().
466
 *
467
 * Collects and adds the number of search results to the head.
468
 */
469
function matomo_preprocess_search_results(&$variables) {
470
  // There is no search result $variable available that hold the number of items
471
  // found. But the pager item mumber can tell the number of search results.
472
  global $pager_total_items;
473

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

    
477
/**
478
 * Download/Synchronize/Cache tracking code file locally.
479
 *
480
 * @param $location
481
 *   The full URL to the external javascript file.
482
 * @param $sync_cached_file
483
 *   Synchronize tracking code and update if remote file have changed.
484
 * @return mixed
485
 *   The path to the local javascript file on success, boolean FALSE on failure.
486
 */
487
function _matomo_cache($location, $sync_cached_file = FALSE) {
488
  $path = 'public://matomo';
489
  $file_destination = $path . '/' . basename($location);
490

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

    
495
    if ($result->code == 200) {
496
      if (file_exists($file_destination)) {
497
        // Synchronize tracking code and and replace local file if outdated.
498
        $data_hash_local = drupal_hash_base64(file_get_contents($file_destination));
499
        $data_hash_remote = drupal_hash_base64($result->data);
500
        // Check that the files directory is writable.
501
        if ($data_hash_local != $data_hash_remote && file_prepare_directory($path)) {
502
          // Save updated tracking code file to disk.
503
          file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
504
          // Based on Drupal Core drupal_build_css_cache().
505
          if (variable_get('css_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
506
            file_unmanaged_save_data(gzencode($result->data, 9, FORCE_GZIP), $file_destination . '.gz', FILE_EXISTS_REPLACE);
507
          }
508
          watchdog('matomo', 'Locally cached tracking code file has been updated.', array(), WATCHDOG_INFO);
509

    
510
          // Change query-strings on css/js files to enforce reload for all users.
511
          _drupal_flush_css_js();
512
        }
513
      }
514
      else {
515
        // Check that the files directory is writable.
516
        if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
517
          // There is no need to flush JS here as core refreshes JS caches
518
          // automatically, if new files are added.
519
          file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
520
          if (variable_get('css_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
521
            file_unmanaged_save_data(gzencode($result->data, 9, FORCE_GZIP), $file_destination . '.gz', FILE_EXISTS_REPLACE);
522
          }
523
          watchdog('matomo', 'Locally cached tracking code file has been saved.', array(), WATCHDOG_INFO);
524

    
525
          // Return the local JS file path.
526
          return file_create_url($file_destination);
527
        }
528
      }
529
    }
530
  }
531
  else {
532
    // Return the local JS file path.
533
    return file_create_url($file_destination);
534
  }
535
}
536

    
537
/**
538
 * Delete cached files and directory.
539
 */
540
function matomo_clear_js_cache() {
541
  $path = 'public://matomo';
542
  if (file_prepare_directory($path)) {
543
    file_scan_directory($path, '/.*/', array('callback' => 'file_unmanaged_delete'));
544
    drupal_rmdir($path);
545

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

    
549
    watchdog('matomo', 'Local cache has been purged.', array(), WATCHDOG_INFO);
550
  }
551
}
552

    
553
/**
554
 * Helper function for grabbing search keys. Function is missing in D7.
555
 *
556
 * http://api.drupal.org/api/function/search_get_keys/6
557
 */
558
function matomo_search_get_keys() {
559
  static $return;
560
  if (!isset($return)) {
561
    // Extract keys as remainder of path
562
    // Note: support old GET format of searches for existing links.
563
    $path = explode('/', $_GET['q'], 3);
564
    $keys = empty($_REQUEST['keys']) ? '' : $_REQUEST['keys'];
565
    $return = count($path) == 3 ? $path[2] : $keys;
566
  }
567
  return $return;
568
}
569

    
570
/**
571
 * Tracking visibility check for an user object.
572
 *
573
 * @param $account
574
 *   A user object containing an array of roles to check.
575
 * @return boolean
576
 *   A decision on if the current user is being tracked by Matomo.
577
 */
578
function _matomo_visibility_user($account) {
579

    
580
  $enabled = FALSE;
581

    
582
  // Is current user a member of a role that should be tracked?
583
  if (_matomo_visibility_roles($account)) {
584

    
585
    // Use the user's block visibility setting, if necessary.
586
    if (($custom = variable_get('matomo_custom', 1)) != 0) {
587
      if ($account->uid && isset($account->data['matomo']['custom'])) {
588
        $enabled = $account->data['matomo']['custom'];
589
      }
590
      else {
591
        $enabled = ($custom == 1);
592
      }
593
    }
594
    else {
595
      $enabled = TRUE;
596
    }
597

    
598
  }
599

    
600
  return $enabled;
601
}
602

    
603
/**
604
 * Based on visibility setting this function returns TRUE if GA code should
605
 * be added for the current role and otherwise FALSE.
606
 */
607
function _matomo_visibility_roles($account) {
608

    
609
  $visibility = variable_get('matomo_visibility_roles', 0);
610
  $enabled = $visibility;
611
  $roles = variable_get('matomo_roles', array());
612

    
613
  if (array_sum($roles) > 0) {
614
    // One or more roles are selected.
615
    foreach (array_keys($account->roles) as $rid) {
616
      // Is the current user a member of one of these roles?
617
      if (isset($roles[$rid]) && $rid == $roles[$rid]) {
618
        // Current user is a member of a role that should be tracked/excluded from tracking.
619
        $enabled = !$visibility;
620
        break;
621
      }
622
    }
623
  }
624
  else {
625
    // No role is selected for tracking, therefore all roles should be tracked.
626
    $enabled = TRUE;
627
  }
628

    
629
  return $enabled;
630
}
631

    
632
/**
633
 * Based on visibility setting this function returns TRUE if GA code should
634
 * be added to the current page and otherwise FALSE.
635
 */
636
function _matomo_visibility_pages() {
637
  static $page_match;
638

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

    
642
    $visibility = variable_get('matomo_visibility_pages', 0);
643
    $setting_pages = variable_get('matomo_pages', MATOMO_PAGES);
644

    
645
    // Match path if necessary.
646
    if (!empty($setting_pages)) {
647
      // Convert path to lowercase. This allows comparison of the same path
648
      // with different case. Ex: /Page, /page, /PAGE.
649
      $pages = drupal_strtolower($setting_pages);
650
      if ($visibility < 2) {
651
        // Convert the Drupal path to lowercase
652
        $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
653
        // Compare the lowercase internal and lowercase path alias (if any).
654
        $page_match = drupal_match_path($path, $pages);
655
        if ($path != $_GET['q']) {
656
          $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
657
        }
658
        // When $visibility has a value of 0, the tracking code is displayed on
659
        // all pages except those listed in $pages. When set to 1, it
660
        // is displayed only on those pages listed in $pages.
661
        $page_match = !($visibility xor $page_match);
662
      }
663
      elseif (module_exists('php')) {
664
        $page_match = php_eval($setting_pages);
665
      }
666
      else {
667
        $page_match = FALSE;
668
      }
669
    }
670
    else {
671
      $page_match = TRUE;
672
    }
673

    
674
  }
675
  return $page_match;
676
}
677

    
678
/**
679
 * Get the page titles trail for the current page.
680
 *
681
 * Based on menu_get_active_breadcrumb().
682
 *
683
 * @return array
684
 *   All page titles, including current page.
685
 */
686
function _matomo_get_hierarchy_titles() {
687
  $titles = array();
688

    
689
  // No breadcrumb for the front page.
690
  if (drupal_is_front_page()) {
691
    return $titles;
692
  }
693

    
694
  $item = menu_get_item();
695
  if (!empty($item['access'])) {
696
    $active_trail = menu_get_active_trail();
697

    
698
    // Allow modules to alter the breadcrumb, if possible, as that is much
699
    // faster than rebuilding an entirely new active trail.
700
    drupal_alter('menu_breadcrumb', $active_trail, $item);
701

    
702
    // Remove the tab root (parent) if the current path links to its parent.
703
    // Normally, the tab root link is included in the breadcrumb, as soon as we
704
    // are on a local task or any other child link. However, if we are on a
705
    // default local task (e.g., node/%/view), then we do not want the tab root
706
    // link (e.g., node/%) to appear, as it would be identical to the current
707
    // page. Since this behavior also needs to work recursively (i.e., on
708
    // default local tasks of default local tasks), and since the last non-task
709
    // link in the trail is used as page title (see menu_get_active_title()),
710
    // this condition cannot be cleanly integrated into menu_get_active_trail().
711
    // menu_get_active_trail() already skips all links that link to their parent
712
    // (commonly MENU_DEFAULT_LOCAL_TASK). In order to also hide the parent link
713
    // itself, we always remove the last link in the trail, if the current
714
    // router item links to its parent.
715
    if (($item['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT) {
716
      array_pop($active_trail);
717
    }
718

    
719
    foreach ($active_trail as $parent) {
720
      $titles[] = $parent['title'];
721
    }
722
  }
723

    
724
  return $titles;
725
}