Projet

Général

Profil

Paste
Télécharger (25,3 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / piwik / piwik.module @ d756b39a

1
<?php
2

    
3
/**
4
 * @file
5
 * Drupal Module: Piwik
6
 *
7
 * Adds the required Javascript to all your Drupal pages to allow tracking by
8
 * the Piwik 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('PIWIK_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('PIWIK_PAGES', "admin\nadmin/*\nbatch\nnode/add*\nnode/*/*\nuser/*/*");
23

    
24
/**
25
 * Implements hook_help().
26
 */
27
function piwik_help($path, $arg) {
28
  switch ($path) {
29
    case 'admin/config/system/piwik':
30
      return t('<a href="@pk_url">Piwik - Web 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. Piwik aims to be an open source alternative to Google Analytics.', array('@pk_url' => 'http://www.piwik.org/'));
31
  }
32
}
33

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

    
45
/**
46
 * Implements hook_permission().
47
 */
48
function piwik_permission() {
49
  return array(
50
    'administer piwik' => array(
51
      'title' => t('Administer Piwik'),
52
      'description' => t('Perform maintenance tasks for Piwik.'),
53
    ),
54
    'opt-in or out of 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 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
  );
64
}
65

    
66
/**
67
 * Implements hook_menu().
68
 */
69
function piwik_menu() {
70
  $items['admin/config/system/piwik'] = array(
71
    'title' => 'Piwik',
72
    'description' => 'Configure the settings used to generate your Piwik tracking code.',
73
    'page callback' => 'drupal_get_form',
74
    'page arguments' => array('piwik_admin_settings_form'),
75
    'access arguments' => array('administer piwik'),
76
    'type' => MENU_NORMAL_ITEM,
77
    'file' => 'piwik.admin.inc',
78
  );
79

    
80
  return $items;
81
}
82

    
83
/**
84
 * Implements hook_page_alter() to insert JavaScript to the appropriate scope/region of the page.
85
 */
86
function piwik_page_alter(&$page) {
87
  global $user;
88

    
89
  $id = variable_get('piwik_site_id', '');
90

    
91
  // Get page status code for visibility filtering.
92
  $status = drupal_get_http_header('Status');
93
  $trackable_status_codes = array(
94
    '403 Forbidden',
95
    '404 Not Found',
96
  );
97

    
98
  // 1. Check if the piwik account number has a value.
99
  // 2. Track page views based on visibility value.
100
  // 3. Check if we should track the currently active user's role.
101
  if (preg_match('/^\d{1,}$/', $id) && (_piwik_visibility_pages() || in_array($status, $trackable_status_codes)) && _piwik_visibility_user($user)) {
102

    
103
    $url_http = variable_get('piwik_url_http', '');
104
    $url_https = variable_get('piwik_url_https', '');
105
    $scope = variable_get('piwik_js_scope', 'header');
106

    
107
    $set_custom_url = '';
108
    $set_document_title = '';
109
    $set_custom_data = array();
110

    
111
    // Add link tracking.
112
    $link_settings = array();
113
    $link_settings['trackMailto'] = variable_get('piwik_trackmailto', 1);
114

    
115
    if (module_exists('colorbox') && ($track_colorbox = variable_get('googleanalytics_trackcolorbox', 1))) {
116
      $link_settings['trackColorbox'] = $track_colorbox;
117
    }
118

    
119
    drupal_add_js(array('piwik' => $link_settings), 'setting');
120
    drupal_add_js(drupal_get_path('module', 'piwik') . '/piwik.js');
121

    
122
    // Piwik can show a tree view of page titles that represents the site structure
123
    // if setDocumentTitle() provides the page titles as a "/" delimited list.
124
    // This may makes it easier to browse through the statistics of page titles
125
    // on larger sites.
126
    if (variable_get('piwik_page_title_hierarchy', FALSE) == TRUE) {
127
      $titles = _piwik_get_hierarchy_titles();
128

    
129
      if (variable_get('piwik_page_title_hierarchy_exclude_home', TRUE)) {
130
        // Remove the "Home" item from the titles to flatten the tree view.
131
        array_shift($titles);
132
      }
133

    
134
      // Remove all empty titles.
135
      $titles = array_filter($titles);
136

    
137
      if (!empty($titles)) {
138
        // Encode title, at least to keep "/" intact.
139
        $titles = array_map('rawurlencode', $titles);
140

    
141
        $set_document_title = drupal_json_encode(implode('/', $titles));
142
      }
143
    }
144

    
145
    // Add messages tracking.
146
    $message_events = '';
147
    if ($message_types = variable_get('piwik_trackmessages', array())) {
148
      $message_types = array_values(array_filter($message_types));
149
      $status_heading = array(
150
        'status' => t('Status message'),
151
        'warning' => t('Warning message'),
152
        'error' => t('Error message'),
153
      );
154

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

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

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

    
186
    // Add custom variables.
187
    $piwik_custom_vars = variable_get('piwik_custom_var', array());
188
    $custom_variable = '';
189
    for ($i = 1; $i < 6; $i++) {
190
      $custom_var_name = !empty($piwik_custom_vars['slots'][$i]['name']) ? $piwik_custom_vars['slots'][$i]['name'] : '';
191
      if (!empty($custom_var_name)) {
192
        $custom_var_value = !empty($piwik_custom_vars['slots'][$i]['value']) ? $piwik_custom_vars['slots'][$i]['value'] : '';
193
        $custom_var_scope = !empty($piwik_custom_vars['slots'][$i]['scope']) ? $piwik_custom_vars['slots'][$i]['scope'] : 'visit';
194

    
195
        $types = array();
196
        $node = menu_get_object();
197
        if (is_object($node)) {
198
          $types += array('node' => $node);
199
        }
200
        $custom_var_name = token_replace($custom_var_name, $types, array('clear' => TRUE));
201
        $custom_var_value = token_replace($custom_var_value, $types, array('clear' => TRUE));
202

    
203
        // Suppress empty custom names and/or variables.
204
        if (!drupal_strlen(trim($custom_var_name)) || !drupal_strlen(trim($custom_var_value))) {
205
          continue;
206
        }
207

    
208
        // Custom variables names and values are limited to 200 characters in
209
        // length. It is recommended to store values that are as small as
210
        // possible to ensure that the Piwik Tracking request URL doesn't go
211
        // over the URL limit for the webserver or browser.
212
        $custom_var_name = rtrim(substr($custom_var_name, 0, 200));
213
        $custom_var_value = rtrim(substr($custom_var_value, 0, 200));
214

    
215
        $custom_var_name = drupal_json_encode($custom_var_name);
216
        $custom_var_value = drupal_json_encode($custom_var_value);
217
        $custom_var_scope = drupal_json_encode($custom_var_scope);
218
        $custom_variable .= "_paq.push(['setCustomVariable', $i, $custom_var_name, $custom_var_value, $custom_var_scope]);";
219
      }
220
    }
221

    
222
    // Add any custom code snippets if specified.
223
    $codesnippet_before = variable_get('piwik_codesnippet_before', '');
224
    $codesnippet_after = variable_get('piwik_codesnippet_after', '');
225

    
226
    // Build tracker code. See http://piwik.org/docs/javascript-tracking/#toc-asynchronous-tracking
227
    $script = 'var _paq = _paq || [];';
228
    $script .= '(function(){';
229
    $script .= 'var u=(("https:" == document.location.protocol) ? "' . check_url($url_https) . '" : "' . check_url($url_http) . '");';
230
    $script .= '_paq.push(["setSiteId", ' . drupal_json_encode(variable_get('piwik_site_id', '')) . ']);';
231
    $script .= '_paq.push(["setTrackerUrl", u+"piwik.php"]);';
232

    
233
    // Track logged in users across all devices.
234
    if (variable_get('piwik_trackuserid', 0) && user_is_logged_in()) {
235
      // The USER_ID value should be a unique, persistent, and non-personally
236
      // identifiable string identifier that represents a user or signed-in
237
      // account across devices.
238
      $script .= '_paq.push(["setUserId", ' . drupal_json_encode(piwik_user_id_hash($user->uid)) . ']);';
239
    }
240

    
241
    // Set custom data.
242
    if (!empty($set_custom_data)) {
243
      foreach ($set_custom_data as $custom_data) {
244
        $script .= '_paq.push(["setCustomData", ' . $custom_data . ']);';
245
      }
246
    }
247
    // Set custom url.
248
    if (!empty($set_custom_url)) {
249
      $script .= '_paq.push(["setCustomUrl", ' . $set_custom_url . ']);';
250
    }
251
    // Set custom document title.
252
    if (!empty($set_document_title)) {
253
      $script .= '_paq.push(["setDocumentTitle", ' . $set_document_title . ']);';
254
    }
255

    
256
    // Custom file download extensions.
257
    if ((variable_get('piwik_track', 1)) && !(variable_get('piwik_trackfiles_extensions', PIWIK_TRACKFILES_EXTENSIONS) == PIWIK_TRACKFILES_EXTENSIONS)) {
258
      $script .= '_paq.push(["setDownloadExtensions", ' . drupal_json_encode(variable_get('piwik_trackfiles_extensions', PIWIK_TRACKFILES_EXTENSIONS)) . ']);';
259
    }
260

    
261
    // Disable tracking for visitors who have opted out from tracking via DNT (Do-Not-Track) header.
262
    if (variable_get('piwik_privacy_donottrack', 1)) {
263
      $script .= '_paq.push(["setDoNotTrack", 1]);';
264
    }
265

    
266
    // Domain tracking type.
267
    global $cookie_domain;
268
    $domain_mode = variable_get('piwik_domain_mode', 0);
269

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

    
276
    // Ordering $custom_variable before $codesnippet_before allows users to add
277
    // custom code snippets that may use deleteCustomVariable() and/or getCustomVariable().
278
    if (!empty($custom_variable)) {
279
      $script .= $custom_variable;
280
    }
281
    if (!empty($codesnippet_before)) {
282
      $script .= $codesnippet_before;
283
    }
284

    
285
    // Site search tracking support.
286
    // NOTE: It's recommended not to call trackPageView() on the Site Search Result page.
287
    if (module_exists('search') && variable_get('piwik_site_search', FALSE) && arg(0) == 'search' && $keys = piwik_search_get_keys()) {
288
      // Parameters:
289
      // 1. Search keyword searched for. Example: "Banana"
290
      // 2. Search category selected in your search engine. If you do not need
291
      //    this, set to false. Example: "Organic Food"
292
      // 3. Number of results on the Search results page. Zero indicates a
293
      //    'No Result Search Keyword'. Set to false if you don't know.
294
      //
295
      // hook_preprocess_search_results() is not executed if search result is
296
      // empty. Make sure the counter is set to 0 if there are no results.
297
      $script .= '_paq.push(["trackSiteSearch", ' . drupal_json_encode($keys) . ', false, (window.piwik_search_results) ? window.piwik_search_results : 0]);';
298
    }
299
    else {
300
      $script .= '_paq.push(["trackPageView"]);';
301
    }
302

    
303
    // Add link tracking.
304
    if (variable_get('piwik_track', 1)) {
305
      // Disable tracking of links with ".no-tracking" and ".colorbox" classes.
306
      $ignore_classes = array(
307
        'no-tracking',
308
        'colorbox',
309
      );
310
      // Disable the download & outlink tracking for specific CSS classes.
311
      // Custom code snippets with 'setIgnoreClasses' will override the value.
312
      // http://developer.piwik.org/api-reference/tracking-javascript#disable-the-download-amp-outlink-tracking-for-specific-css-classes
313
      $script .= '_paq.push(["setIgnoreClasses", ' . drupal_json_encode($ignore_classes) . ']);';
314

    
315
      // Enable download & outlink link tracking.
316
      $script .= '_paq.push(["enableLinkTracking"]);';
317
    }
318

    
319
    if (!empty($message_events)) {
320
      $script .= $message_events;
321
    }
322
    if (!empty($codesnippet_after)) {
323
      $script .= $codesnippet_after;
324
    }
325

    
326
    $script .= 'var d=document,';
327
    $script .= 'g=d.createElement("script"),';
328
    $script .= 's=d.getElementsByTagName("script")[0];';
329
    $script .= 'g.type="text/javascript";';
330
    $script .= 'g.defer=true;';
331
    $script .= 'g.async=true;';
332

    
333
    // Should a local cached copy of the tracking code be used?
334
    if (variable_get('piwik_cache', 0) && $url = _piwik_cache($url_http . 'piwik.js')) {
335
      // A dummy query-string is added to filenames, to gain control over
336
      // browser-caching. The string changes on every update or full cache
337
      // flush, forcing browsers to load a new copy of the files, as the
338
      // URL changed.
339
      $query_string = '?' . variable_get('css_js_query_string', '0');
340

    
341
      $script .= 'g.src="' . $url . $query_string . '";';
342
    }
343
    else {
344
      $script .= 'g.src=u+"piwik.js";';
345
    }
346

    
347
    $script .= 's.parentNode.insertBefore(g,s);';
348
    $script .= '})();';
349

    
350
    // Add tracker code to scope.
351
    drupal_add_js($script, array('scope' => $scope, 'type' => 'inline'));
352
  }
353
}
354

    
355
/**
356
 * Generate user id hash to implement USER_ID.
357
 *
358
 * The USER_ID value should be a unique, persistent, and non-personally
359
 * identifiable string identifier that represents a user or signed-in
360
 * account across devices.
361
 *
362
 * @param int $uid
363
 *   User id.
364
 *
365
 * @return string
366
 *   User id hash.
367
 */
368
function piwik_user_id_hash($uid) {
369
  return drupal_hmac_base64($uid, drupal_get_private_key() . drupal_get_hash_salt());
370
}
371

    
372
/**
373
 * Implements hook_field_extra_fields().
374
 */
375
function piwik_field_extra_fields() {
376
  $extra['user']['user']['form']['piwik'] = array(
377
    'label' => t('Piwik configuration'),
378
    'description' => t('Piwik module form element.'),
379
    'weight' => 3,
380
  );
381

    
382
  return $extra;
383
}
384

    
385
/**
386
 * Implement hook_form_FORM_ID_alter().
387
 *
388
 * Allow users to decide if tracking code will be added to pages or not.
389
 */
390
function piwik_form_user_profile_form_alter(&$form, &$form_state) {
391
  $account = $form['#user'];
392
  $category = $form['#user_category'];
393

    
394
  if ($category == 'account' && user_access('opt-in or out of tracking') && ($custom = variable_get('piwik_custom', 0)) != 0 && _piwik_visibility_roles($account)) {
395
    $form['piwik'] = array(
396
      '#type' => 'fieldset',
397
      '#title' => t('Piwik configuration'),
398
      '#weight' => 3,
399
      '#collapsible' => TRUE,
400
      '#tree' => TRUE
401
    );
402

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

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

    
413
    $form['piwik']['custom'] = array(
414
      '#type' => 'checkbox',
415
      '#title' => t('Enable user tracking'),
416
      '#description' => $description,
417
      '#default_value' => isset($account->data['piwik']['custom']) ? $account->data['piwik']['custom'] : ($custom == 1),
418
    );
419

    
420
    return $form;
421
  }
422
}
423

    
424
/**
425
 * Implements hook_user_presave().
426
 */
427
function piwik_user_presave(&$edit, $account, $category) {
428
  if (isset($edit['piwik']['custom'])) {
429
    $edit['data']['piwik']['custom'] = $edit['piwik']['custom'];
430
  }
431
}
432

    
433
/**
434
 * Implements hook_cron().
435
 */
436
function piwik_cron() {
437
  // Regenerate the piwik.js every day.
438
  if (REQUEST_TIME - variable_get('piwik_last_cache', 0) >= 86400 && variable_get('piwik_cache', 0)) {
439
    _piwik_cache(variable_get('piwik_url_http', '') . 'piwik.js', TRUE);
440
    variable_set('piwik_last_cache', REQUEST_TIME);
441
  }
442
}
443

    
444
/**
445
 * Implements hook_preprocess_search_results().
446
 *
447
 * Collects and adds the number of search results to the head.
448
 */
449
function piwik_preprocess_search_results(&$variables) {
450
  // There is no search result $variable available that hold the number of items
451
  // found. But the pager item mumber can tell the number of search results.
452
  global $pager_total_items;
453

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

    
457
/**
458
 * Download/Synchronize/Cache tracking code file locally.
459
 *
460
 * @param $location
461
 *   The full URL to the external javascript file.
462
 * @param $sync_cached_file
463
 *   Synchronize tracking code and update if remote file have changed.
464
 * @return mixed
465
 *   The path to the local javascript file on success, boolean FALSE on failure.
466
 */
467
function _piwik_cache($location, $sync_cached_file = FALSE) {
468
  $path = 'public://piwik';
469
  $file_destination = $path . '/' . basename($location);
470

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

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

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

    
498
          // Return the local JS file path.
499
          return file_create_url($file_destination);
500
        }
501
      }
502
    }
503
  }
504
  else {
505
    // Return the local JS file path.
506
    return file_create_url($file_destination);
507
  }
508
}
509

    
510
/**
511
 * Delete cached files and directory.
512
 */
513
function piwik_clear_js_cache() {
514
  $path = 'public://piwik';
515
  if (file_prepare_directory($path)) {
516
    file_scan_directory($path, '/.*/', array('callback' => 'file_unmanaged_delete'));
517
    drupal_rmdir($path);
518

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

    
522
    watchdog('piwik', 'Local cache has been purged.', array(), WATCHDOG_INFO);
523
  }
524
}
525

    
526
/**
527
 * Helper function for grabbing search keys. Function is missing in D7.
528
 *
529
 * http://api.drupal.org/api/function/search_get_keys/6
530
 */
531
function piwik_search_get_keys() {
532
  static $return;
533
  if (!isset($return)) {
534
    // Extract keys as remainder of path
535
    // Note: support old GET format of searches for existing links.
536
    $path = explode('/', $_GET['q'], 3);
537
    $keys = empty($_REQUEST['keys']) ? '' : $_REQUEST['keys'];
538
    $return = count($path) == 3 ? $path[2] : $keys;
539
  }
540
  return $return;
541
}
542

    
543
/**
544
 * Tracking visibility check for an user object.
545
 *
546
 * @param $account
547
 *   A user object containing an array of roles to check.
548
 * @return boolean
549
 *   A decision on if the current user is being tracked by Piwik.
550
 */
551
function _piwik_visibility_user($account) {
552

    
553
  $enabled = FALSE;
554

    
555
  // Is current user a member of a role that should be tracked?
556
  if (_piwik_visibility_roles($account)) {
557

    
558
    // Use the user's block visibility setting, if necessary.
559
    if (($custom = variable_get('piwik_custom', 0)) != 0) {
560
      if ($account->uid && isset($account->data['piwik']['custom'])) {
561
        $enabled = $account->data['piwik']['custom'];
562
      }
563
      else {
564
        $enabled = ($custom == 1);
565
      }
566
    }
567
    else {
568
      $enabled = TRUE;
569
    }
570

    
571
  }
572

    
573
  return $enabled;
574
}
575

    
576
/**
577
 * Based on visibility setting this function returns TRUE if GA code should
578
 * be added for the current role and otherwise FALSE.
579
 */
580
function _piwik_visibility_roles($account) {
581

    
582
  $visibility = variable_get('piwik_visibility_roles', 0);
583
  $enabled = $visibility;
584
  $roles = variable_get('piwik_roles', array());
585

    
586
  if (array_sum($roles) > 0) {
587
    // One or more roles are selected.
588
    foreach (array_keys($account->roles) as $rid) {
589
      // Is the current user a member of one of these roles?
590
      if (isset($roles[$rid]) && $rid == $roles[$rid]) {
591
        // Current user is a member of a role that should be tracked/excluded from tracking.
592
        $enabled = !$visibility;
593
        break;
594
      }
595
    }
596
  }
597
  else {
598
    // No role is selected for tracking, therefore all roles should be tracked.
599
    $enabled = TRUE;
600
  }
601

    
602
  return $enabled;
603
}
604

    
605
/**
606
 * Based on visibility setting this function returns TRUE if GA code should
607
 * be added to the current page and otherwise FALSE.
608
 */
609
function _piwik_visibility_pages() {
610
  static $page_match;
611

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

    
615
    $visibility = variable_get('piwik_visibility_pages', 0);
616
    $setting_pages = variable_get('piwik_pages', PIWIK_PAGES);
617

    
618
    // Match path if necessary.
619
    if (!empty($setting_pages)) {
620
      // Convert path to lowercase. This allows comparison of the same path
621
      // with different case. Ex: /Page, /page, /PAGE.
622
      $pages = drupal_strtolower($setting_pages);
623
      if ($visibility < 2) {
624
        // Convert the Drupal path to lowercase
625
        $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
626
        // Compare the lowercase internal and lowercase path alias (if any).
627
        $page_match = drupal_match_path($path, $pages);
628
        if ($path != $_GET['q']) {
629
          $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
630
        }
631
        // When $visibility has a value of 0, the tracking code is displayed on
632
        // all pages except those listed in $pages. When set to 1, it
633
        // is displayed only on those pages listed in $pages.
634
        $page_match = !($visibility xor $page_match);
635
      }
636
      elseif (module_exists('php')) {
637
        $page_match = php_eval($setting_pages);
638
      }
639
      else {
640
        $page_match = FALSE;
641
      }
642
    }
643
    else {
644
      $page_match = TRUE;
645
    }
646

    
647
  }
648
  return $page_match;
649
}
650

    
651
/**
652
 * Get the page titles trail for the current page.
653
 *
654
 * Based on menu_get_active_breadcrumb().
655
 *
656
 * @return array
657
 *   All page titles, including current page.
658
 */
659
function _piwik_get_hierarchy_titles() {
660
  $titles = array();
661

    
662
  // No breadcrumb for the front page.
663
  if (drupal_is_front_page()) {
664
    return $titles;
665
  }
666

    
667
  $item = menu_get_item();
668
  if (!empty($item['access'])) {
669
    $active_trail = menu_get_active_trail();
670

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

    
675
    // Remove the tab root (parent) if the current path links to its parent.
676
    // Normally, the tab root link is included in the breadcrumb, as soon as we
677
    // are on a local task or any other child link. However, if we are on a
678
    // default local task (e.g., node/%/view), then we do not want the tab root
679
    // link (e.g., node/%) to appear, as it would be identical to the current
680
    // page. Since this behavior also needs to work recursively (i.e., on
681
    // default local tasks of default local tasks), and since the last non-task
682
    // link in the trail is used as page title (see menu_get_active_title()),
683
    // this condition cannot be cleanly integrated into menu_get_active_trail().
684
    // menu_get_active_trail() already skips all links that link to their parent
685
    // (commonly MENU_DEFAULT_LOCAL_TASK). In order to also hide the parent link
686
    // itself, we always remove the last link in the trail, if the current
687
    // router item links to its parent.
688
    if (($item['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT) {
689
      array_pop($active_trail);
690
    }
691

    
692
    foreach ($active_trail as $parent) {
693
      $titles[] = $parent['title'];
694
    }
695
  }
696

    
697
  return $titles;
698
}