You are here

piwik.module in Piwik Web Analytics 6.2

Drupal Module: Piwik

Adds the required Javascript to all your Drupal pages to allow tracking by the Piwik statistics package.

@author: Alexander Hass <www.hass.de>

File

piwik.module
View source
<?php

/**
 * @file
 * Drupal Module: Piwik
 *
 * Adds the required Javascript to all your Drupal pages to allow tracking by
 * the Piwik statistics package.
 *
 * @author: Alexander Hass <www.hass.de>
 */
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');

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

/**
 * Implementation of hook_help().
 */
function piwik_help($path, $arg) {
  switch ($path) {
    case 'admin/settings/piwik':
      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/',
      ));
  }
}

/**
 * Implementation of hook_perm().
 */
function piwik_perm() {
  return array(
    'administer piwik',
    'opt-in or out of tracking',
    'use PHP for tracking visibility',
    'add JS snippets for piwik',
  );
}

/**
 * Implementation of hook_menu().
 */
function piwik_menu() {
  $items['admin/settings/piwik'] = array(
    'title' => 'Piwik',
    'description' => 'Configure the settings used to generate your Piwik tracking code.',
    'page callback' => 'drupal_get_form',
    'page arguments' => array(
      'piwik_admin_settings_form',
    ),
    'access arguments' => array(
      'administer piwik',
    ),
    'file' => 'piwik.admin.inc',
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

/**
 * Implementation of hook_init().
 */
function piwik_init() {
  global $user;
  $id = variable_get('piwik_site_id', '');

  // 1. Check if the piwik 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) && _piwik_visibility_pages() && _piwik_visibility_user($user)) {

    // Add link tracking.
    $link_settings = array();
    $link_settings['trackMailto'] = variable_get('piwik_trackmailto', 1);
    drupal_add_js(array(
      'piwik' => $link_settings,
    ), 'setting', 'header');
    drupal_add_js(drupal_get_path('module', 'piwik') . '/piwik.js', 'module', 'header');
  }
}

/**
 * Implementation of hook_footer() to insert Javascript at the end of the page.
 */
function piwik_footer($main = 0) {
  global $user;
  $id = variable_get('piwik_site_id', '');

  // 1. Check if the piwik 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) && _piwik_visibility_pages() && _piwik_visibility_user($user)) {
    $url_http = variable_get('piwik_url_http', '');
    $url_https = variable_get('piwik_url_https', '');
    $set_custom_url = '';
    $set_document_title = '';
    $set_custom_data = array();

    // Piwik 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 (variable_get('piwik_page_title_hierarchy', FALSE) == TRUE) {
      $titles = _piwik_get_hierarchy_titles();
      if (variable_get('piwik_page_title_hierarchy_exclude_home', TRUE)) {

        // 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 = drupal_to_js(implode('/', $titles));
      }
    }

    // If this node is a translation of another node, pass the original
    // node instead.
    if (module_exists('translation') && variable_get('piwik_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();
        $set_custom_url = drupal_to_js(url('node/' . $source_node->nid, array(
          'language' => $languages[$source_node->language],
          'absolute' => TRUE,
        )));
      }
    }

    // Track access denied (403) and file not found (404) pages.
    if (function_exists('drupal_get_headers')) {
      $headers = drupal_get_headers();
      if (strstr($headers, '403 Forbidden')) {
        $set_document_title = '"403/URL = " + encodeURIComponent(document.location.pathname+document.location.search) + "/From = " + encodeURIComponent(document.referrer)';
      }
      elseif (strstr($headers, '404 Not Found')) {
        $set_document_title = '"404/URL = " + encodeURIComponent(document.location.pathname+document.location.search) + "/From = " + encodeURIComponent(document.referrer)';
      }
    }

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

    // Build tracker code. See http://piwik.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", ' . drupal_to_js(variable_get('piwik_site_id', '')) . ']);';
    $script .= '_paq.push(["setTrackerUrl", u+"piwik.php"]);';

    // Track logged in users across all devices.
    if (variable_get('piwik_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.
      $script .= '_paq.push(["setUserId", ' . drupal_to_js(_piwik_hmac_base64($user->uid, drupal_get_private_key() . _piwik_get_hash_salt())) . ']);';
    }

    // Set custom data.
    if (!empty($set_custom_data)) {
      foreach ($set_custom_data as $custom_data) {
        $script .= '_paq.push(["setCustomData", ' . $custom_data . ']);';
      }
    }

    // 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 (variable_get('piwik_track', 1) && !(variable_get('piwik_trackfiles_extensions', PIWIK_TRACKFILES_EXTENSIONS) == PIWIK_TRACKFILES_EXTENSIONS)) {
      $script .= '_paq.push(["setDownloadExtensions", ' . drupal_to_js(variable_get('piwik_trackfiles_extensions', PIWIK_TRACKFILES_EXTENSIONS)) . ']);';
    }

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

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

    // Per RFC 2109, cookie domains must contain at least one dot other than the
    // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
    if ($domain_mode == 1 && count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
      $script .= '_paq.push(["setCookieDomain", ' . drupal_to_js($cookie_domain) . ']);';
    }
    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') && variable_get('piwik_site_search', FALSE) && arg(0) == 'search' && ($keys = 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", ' . drupal_to_js($keys) . ', false, (window.piwik_search_results) ? window.piwik_search_results : 0]);';
    }
    else {
      $script .= '_paq.push(["trackPageView"]);';
    }

    // Add link tracking.
    if (variable_get('piwik_track', 1)) {

      // 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.
      // http://developer.piwik.org/api-reference/tracking-javascript#disable-the-download-amp-outlink-tracking-for-specific-css-classes
      $script .= '_paq.push(["setIgnoreClasses", ' . drupal_to_js($ignore_classes) . ']);';

      // Enable download & outlink link tracking.
      $script .= '_paq.push(["enableLinkTracking"]);';
    }
    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 (variable_get('piwik_cache', 0) && variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC && ($url = _piwik_cache($url_http . 'piwik.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 = '?' . substr(variable_get('css_js_query_string', '0'), 0, 1);
      $script .= 'g.src="' . $url . $query_string . '";';
    }
    else {
      $script .= 'g.src=u+"piwik.js";';
    }
    $script .= 's.parentNode.insertBefore(g,s);';
    $script .= '})();';
    drupal_add_js($script, 'inline', 'footer');
  }
}

/**
 * Implementation of hook_user().
 *
 * Allow users to decide if tracking code will be added to pages or not.
 */
function piwik_user($type, $edit, &$account, $category = NULL) {
  switch ($type) {
    case 'form':
      if ($category == 'account' && user_access('opt-in or out of tracking') && ($custom = variable_get('piwik_custom', 0)) != 0 && _piwik_visibility_roles($account)) {
        $form['piwik'] = array(
          '#type' => 'fieldset',
          '#title' => t('Piwik 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;
        }
        $form['piwik']['custom'] = array(
          '#type' => 'checkbox',
          '#title' => t('Enable user tracking'),
          '#description' => $description,
          '#default_value' => isset($account->piwik['custom']) ? $account->piwik['custom'] : $custom == 1,
        );
        return $form;
      }
      break;
  }
}

/**
 * Implementation of hook_cron().
 */
function piwik_cron() {

  // Regenerate the piwik.js every day.
  if (time() - variable_get('piwik_last_cache', 0) >= 86400 && variable_get('piwik_cache', 0)) {
    _piwik_cache(variable_get('piwik_url_http', '') . '/piwik.js', TRUE);
    variable_set('piwik_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 piwik_preprocess_search_results(&$variables) {

  // There is no search result $variable available that hold the number of items
  // found. But the pager item mumber can tell the number of search results.
  global $pager_total_items;
  drupal_add_js('window.piwik_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 $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 _piwik_cache($location, $sync_cached_file = FALSE) {
  $path = file_create_path('piwik');
  $file_destination = $path . '/' . basename($location);
  if (!file_exists($file_destination) || $sync_cached_file) {

    // Download the latest tracking code.
    $result = drupal_http_request($location);
    if ($result->code == 200) {
      if (file_exists($file_destination)) {

        // Synchronize tracking code and and replace local file if outdated.
        $data_hash_local = 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('piwik', '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('piwik', '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 piwik_clear_js_cache() {
  $path = file_create_path('piwik');
  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('piwik', '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 Piwik.
 */
function _piwik_visibility_user($account) {
  $enabled = FALSE;

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

    // Use the user's block visibility setting, if necessary.
    if (($custom = variable_get('piwik_custom', 0)) != 0) {
      if ($account->uid && isset($account->piwik['custom'])) {
        $enabled = $account->piwik['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 _piwik_visibility_roles($account) {
  $visibility = variable_get('piwik_visibility_roles', 0);
  $enabled = $visibility;
  $roles = variable_get('piwik_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 _piwik_visibility_pages() {
  static $page_match;

  // Cache visibility setting in hook_init for hook_footer.
  if (!isset($page_match)) {
    $visibility = variable_get('piwik_visibility_pages', 0);
    $setting_pages = variable_get('piwik_pages', PIWIK_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;
}

/**
 * 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 _piwik_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 _piwik_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(
    '+' => '-',
    '/' => '_',
    '=' => '',
  ));
}

/**
 * Get the page titles trail for the current page.
 *
 * Based on menu_get_active_breadcrumb().
 *
 * @return array
 *   All page titles, including current page.
 */
function _piwik_get_hierarchy_titles() {
  $titles = array();

  // No breadcrumb for the front page.
  if (drupal_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.
    drupal_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;
}

Functions

Namesort descending Description
piwik_clear_js_cache Delete cached files and directory.
piwik_cron Implementation of hook_cron().
piwik_footer Implementation of hook_footer() to insert Javascript at the end of the page.
piwik_help Implementation of hook_help().
piwik_init Implementation of hook_init().
piwik_menu Implementation of hook_menu().
piwik_perm Implementation of hook_perm().
piwik_preprocess_search_results Implementation of hook_preprocess_search_results().
piwik_user Implementation of hook_user().
_piwik_cache Download/Synchronize/Cache tracking code file locally.
_piwik_get_hash_salt Backport of https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drup...
_piwik_get_hierarchy_titles Get the page titles trail for the current page.
_piwik_hmac_base64 Backport of https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drup...
_piwik_visibility_pages Based on visibility setting this function returns TRUE if GA code should be added to the current page and otherwise FALSE.
_piwik_visibility_roles Based on visibility setting this function returns TRUE if GA code should be added for the current role and otherwise FALSE.
_piwik_visibility_user Tracking visibility check for an user object.

Constants

Namesort descending Description
PIWIK_PAGES Define default path exclusion list to remove tracking from admin pages, see http://drupal.org/node/34970 for more information.
PIWIK_TRACKFILES_EXTENSIONS @file Drupal Module: Piwik