7 * Adds the required Javascript to all your Drupal pages to allow tracking by
8 * the Piwik statistics package.
10 * @author: Alexander Hass <http://drupal.org/user/85918>
14 * Define the default file extension list that should be tracked as download.
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');
19 * Define default path exclusion list to remove tracking from admin pages,
20 * see http://drupal.org/node/34970 for more information.
22 define('PIWIK_PAGES', "admin\nadmin/*\nbatch\nnode/add*\nnode/*/*\nuser/*/*");
25 * Implements hook_help().
27 function piwik_help($path, $arg) {
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/'));
35 * Implements hook_theme().
37 function piwik_theme() {
39 'piwik_admin_custom_var_table' => array(
40 'render element' => 'form',
46 * Implements hook_permission().
48 function piwik_permission() {
50 'administer piwik' => array(
51 'title' => t('Administer Piwik'),
52 'description' => t('Perform maintenance tasks for Piwik.'),
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.'),
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,
63 'add JS snippets for piwik' => array(
64 'title' => t('Add JavaScript snippets'),
65 'description' => 'Enter JavaScript code snippets for advanced Piwik functionality.',
66 'restrict access' => TRUE,
72 * Implements hook_menu().
74 function piwik_menu() {
75 $items['admin/config/system/piwik'] = array(
77 'description' => 'Configure the settings used to generate your Piwik tracking code.',
78 'page callback' => 'drupal_get_form',
79 'page arguments' => array('piwik_admin_settings_form'),
80 'access arguments' => array('administer piwik'),
81 'type' => MENU_NORMAL_ITEM,
82 'file' => 'piwik.admin.inc',
89 * Implements hook_page_alter() to insert JavaScript to the appropriate scope/region of the page.
91 function piwik_page_alter(&$page) {
94 $id = variable_get('piwik_site_id', '');
96 // Get page status code for visibility filtering.
97 $status = drupal_get_http_header('Status');
98 $trackable_status_codes = array(
103 // 1. Check if the piwik 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) && (_piwik_visibility_pages() || in_array($status, $trackable_status_codes)) && _piwik_visibility_user($user)) {
108 $url_http = variable_get('piwik_url_http', '');
109 $url_https = variable_get('piwik_url_https', '');
110 $scope = variable_get('piwik_js_scope', 'header');
112 $set_custom_url = '';
113 $set_document_title = '';
114 $set_custom_data = array();
116 // Add link tracking.
117 $link_settings = array();
118 $link_settings['trackMailto'] = variable_get('piwik_trackmailto', 1);
120 if (module_exists('colorbox') && ($track_colorbox = variable_get('piwik_trackcolorbox', 1))) {
121 $link_settings['trackColorbox'] = $track_colorbox;
124 drupal_add_js(array('piwik' => $link_settings), 'setting');
125 drupal_add_js(drupal_get_path('module', 'piwik') . '/piwik.js');
127 // Piwik can show a tree view of page titles that represents the site structure
128 // if setDocumentTitle() provides the page titles as a "/" delimited list.
129 // This may makes it easier to browse through the statistics of page titles
131 if (variable_get('piwik_page_title_hierarchy', FALSE) == TRUE) {
132 $titles = _piwik_get_hierarchy_titles();
134 if (variable_get('piwik_page_title_hierarchy_exclude_home', TRUE)) {
135 // Remove the "Home" item from the titles to flatten the tree view.
136 array_shift($titles);
139 // Remove all empty titles.
140 $titles = array_filter($titles);
142 if (!empty($titles)) {
143 // Encode title, at least to keep "/" intact.
144 $titles = array_map('rawurlencode', $titles);
146 $set_document_title = drupal_json_encode(implode('/', $titles));
150 // Add messages tracking.
151 $message_events = '';
152 if ($message_types = variable_get('piwik_trackmessages', array())) {
153 $message_types = array_values(array_filter($message_types));
154 $status_heading = array(
155 'status' => t('Status message'),
156 'warning' => t('Warning message'),
157 'error' => t('Error message'),
160 foreach (drupal_get_messages(NULL, FALSE) as $type => $messages) {
161 // Track only the selected message types.
162 if (in_array($type, $message_types)) {
163 foreach ($messages as $message) {
164 $message_events .= '_paq.push(["trackEvent", ' . drupal_json_encode(t('Messages')) . ', ' . drupal_json_encode($status_heading[$type]) . ', ' . drupal_json_encode(strip_tags($message)) . ']);';
170 // If this node is a translation of another node, pass the original
172 if (module_exists('translation') && variable_get('piwik_translation_set', 0)) {
173 // Check we have a node object, it supports translation, and its
174 // translated node ID (tnid) doesn't match its own node ID.
175 $node = menu_get_object();
176 if ($node && translation_supported_type($node->type) && !empty($node->tnid) && ($node->tnid != $node->nid)) {
177 $source_node = node_load($node->tnid);
178 $languages = language_list();
179 $set_custom_url = drupal_json_encode(url('node/' . $source_node->nid, array('language' => $languages[$source_node->language], 'absolute' => TRUE)));
183 // Track access denied (403) and file not found (404) pages.
184 if ($status == '403 Forbidden') {
185 $set_document_title = '"403/URL = " + encodeURIComponent(document.location.pathname+document.location.search) + "/From = " + encodeURIComponent(document.referrer)';
187 elseif ($status == '404 Not Found') {
188 $set_document_title = '"404/URL = " + encodeURIComponent(document.location.pathname+document.location.search) + "/From = " + encodeURIComponent(document.referrer)';
191 // Add custom variables.
192 $piwik_custom_vars = variable_get('piwik_custom_var', array());
193 $custom_variable = '';
194 for ($i = 1; $i < 6; $i++) {
195 $custom_var_name = !empty($piwik_custom_vars['slots'][$i]['name']) ? $piwik_custom_vars['slots'][$i]['name'] : '';
196 if (!empty($custom_var_name)) {
197 $custom_var_value = !empty($piwik_custom_vars['slots'][$i]['value']) ? $piwik_custom_vars['slots'][$i]['value'] : '';
198 $custom_var_scope = !empty($piwik_custom_vars['slots'][$i]['scope']) ? $piwik_custom_vars['slots'][$i]['scope'] : 'visit';
201 $node = menu_get_object();
202 if (is_object($node)) {
203 $types += array('node' => $node);
205 $custom_var_name = token_replace($custom_var_name, $types, array('clear' => TRUE));
206 $custom_var_value = token_replace($custom_var_value, $types, array('clear' => TRUE));
208 // Suppress empty custom names and/or variables.
209 if (!drupal_strlen(trim($custom_var_name)) || !drupal_strlen(trim($custom_var_value))) {
213 // Custom variables names and values are limited to 200 characters in
214 // length. It is recommended to store values that are as small as
215 // possible to ensure that the Piwik Tracking request URL doesn't go
216 // over the URL limit for the webserver or browser.
217 $custom_var_name = rtrim(substr($custom_var_name, 0, 200));
218 $custom_var_value = rtrim(substr($custom_var_value, 0, 200));
220 $custom_var_name = drupal_json_encode($custom_var_name);
221 $custom_var_value = drupal_json_encode($custom_var_value);
222 $custom_var_scope = drupal_json_encode($custom_var_scope);
223 $custom_variable .= "_paq.push(['setCustomVariable', $i, $custom_var_name, $custom_var_value, $custom_var_scope]);";
227 // Add any custom code snippets if specified.
228 $codesnippet_before = variable_get('piwik_codesnippet_before', '');
229 $codesnippet_after = variable_get('piwik_codesnippet_after', '');
231 // Build tracker code. See http://piwik.org/docs/javascript-tracking/#toc-asynchronous-tracking
232 $script = 'var _paq = _paq || [];';
233 $script .= '(function(){';
234 $script .= 'var u=(("https:" == document.location.protocol) ? "' . check_url($url_https) . '" : "' . check_url($url_http) . '");';
235 $script .= '_paq.push(["setSiteId", ' . drupal_json_encode(variable_get('piwik_site_id', '')) . ']);';
236 $script .= '_paq.push(["setTrackerUrl", u+"piwik.php"]);';
238 // Track logged in users across all devices.
239 if (variable_get('piwik_trackuserid', 0) && user_is_logged_in()) {
240 // The USER_ID value should be a unique, persistent, and non-personally
241 // identifiable string identifier that represents a user or signed-in
242 // account across devices.
243 $script .= '_paq.push(["setUserId", ' . drupal_json_encode(piwik_user_id_hash($user->uid)) . ']);';
247 if (!empty($set_custom_data)) {
248 foreach ($set_custom_data as $custom_data) {
249 $script .= '_paq.push(["setCustomData", ' . $custom_data . ']);';
253 if (!empty($set_custom_url)) {
254 $script .= '_paq.push(["setCustomUrl", ' . $set_custom_url . ']);';
256 // Set custom document title.
257 if (!empty($set_document_title)) {
258 $script .= '_paq.push(["setDocumentTitle", ' . $set_document_title . ']);';
261 // Custom file download extensions.
262 if ((variable_get('piwik_track', 1)) && !(variable_get('piwik_trackfiles_extensions', PIWIK_TRACKFILES_EXTENSIONS) == PIWIK_TRACKFILES_EXTENSIONS)) {
263 $script .= '_paq.push(["setDownloadExtensions", ' . drupal_json_encode(variable_get('piwik_trackfiles_extensions', PIWIK_TRACKFILES_EXTENSIONS)) . ']);';
266 // Disable tracking for visitors who have opted out from tracking via DNT (Do-Not-Track) header.
267 if (variable_get('piwik_privacy_donottrack', 1)) {
268 $script .= '_paq.push(["setDoNotTrack", 1]);';
271 // Domain tracking type.
272 global $cookie_domain;
273 $domain_mode = variable_get('piwik_domain_mode', 0);
275 // Per RFC 2109, cookie domains must contain at least one dot other than the
276 // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
277 if ($domain_mode == 1 && count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
278 $script .= '_paq.push(["setCookieDomain", ' . drupal_json_encode($cookie_domain) . ']);';
281 // Ordering $custom_variable before $codesnippet_before allows users to add
282 // custom code snippets that may use deleteCustomVariable() and/or getCustomVariable().
283 if (!empty($custom_variable)) {
284 $script .= $custom_variable;
286 if (!empty($codesnippet_before)) {
287 $script .= $codesnippet_before;
290 // Site search tracking support.
291 // NOTE: It's recommended not to call trackPageView() on the Site Search Result page.
292 if (module_exists('search') && variable_get('piwik_site_search', FALSE) && arg(0) == 'search' && $keys = piwik_search_get_keys()) {
294 // 1. Search keyword searched for. Example: "Banana"
295 // 2. Search category selected in your search engine. If you do not need
296 // this, set to false. Example: "Organic Food"
297 // 3. Number of results on the Search results page. Zero indicates a
298 // 'No Result Search Keyword'. Set to false if you don't know.
300 // hook_preprocess_search_results() is not executed if search result is
301 // empty. Make sure the counter is set to 0 if there are no results.
302 $script .= '_paq.push(["trackSiteSearch", ' . drupal_json_encode($keys) . ', false, (window.piwik_search_results) ? window.piwik_search_results : 0]);';
305 $script .= '_paq.push(["trackPageView"]);';
308 // Add link tracking.
309 if (variable_get('piwik_track', 1)) {
310 // Disable tracking of links with ".no-tracking" and ".colorbox" classes.
311 $ignore_classes = array(
315 // Disable the download & outlink tracking for specific CSS classes.
316 // Custom code snippets with 'setIgnoreClasses' will override the value.
317 // http://developer.piwik.org/api-reference/tracking-javascript#disable-the-download-amp-outlink-tracking-for-specific-css-classes
318 $script .= '_paq.push(["setIgnoreClasses", ' . drupal_json_encode($ignore_classes) . ']);';
320 // Enable download & outlink link tracking.
321 $script .= '_paq.push(["enableLinkTracking"]);';
324 if (!empty($message_events)) {
325 $script .= $message_events;
327 if (!empty($codesnippet_after)) {
328 $script .= $codesnippet_after;
331 $script .= 'var d=document,';
332 $script .= 'g=d.createElement("script"),';
333 $script .= 's=d.getElementsByTagName("script")[0];';
334 $script .= 'g.type="text/javascript";';
335 $script .= 'g.defer=true;';
336 $script .= 'g.async=true;';
338 // Should a local cached copy of the tracking code be used?
339 if (variable_get('piwik_cache', 0) && $url = _piwik_cache($url_http . 'piwik.js')) {
340 // A dummy query-string is added to filenames, to gain control over
341 // browser-caching. The string changes on every update or full cache
342 // flush, forcing browsers to load a new copy of the files, as the
344 $query_string = '?' . variable_get('css_js_query_string', '0');
346 $script .= 'g.src="' . $url . $query_string . '";';
349 $script .= 'g.src=u+"piwik.js";';
352 $script .= 's.parentNode.insertBefore(g,s);';
355 // Add tracker code to scope.
356 drupal_add_js($script, array('scope' => $scope, 'type' => 'inline'));
361 * Generate user id hash to implement USER_ID.
363 * The USER_ID value should be a unique, persistent, and non-personally
364 * identifiable string identifier that represents a user or signed-in
365 * account across devices.
373 function piwik_user_id_hash($uid) {
374 return drupal_hmac_base64($uid, drupal_get_private_key() . drupal_get_hash_salt());
378 * Implements hook_field_extra_fields().
380 function piwik_field_extra_fields() {
381 $extra['user']['user']['form']['piwik'] = array(
382 'label' => t('Piwik configuration'),
383 'description' => t('Piwik module form element.'),
391 * Implement hook_form_FORM_ID_alter().
393 * Allow users to decide if tracking code will be added to pages or not.
395 function piwik_form_user_profile_form_alter(&$form, &$form_state) {
396 $account = $form['#user'];
397 $category = $form['#user_category'];
399 if ($category == 'account' && user_access('opt-in or out of tracking') && ($custom = variable_get('piwik_custom', 0)) != 0 && _piwik_visibility_roles($account)) {
400 $form['piwik'] = array(
401 '#type' => 'fieldset',
402 '#title' => t('Piwik configuration'),
404 '#collapsible' => TRUE,
410 $description = t('Users are tracked by default, but you are able to opt out.');
414 $description = t('Users are <em>not</em> tracked by default, but you are able to opt in.');
418 $form['piwik']['custom'] = array(
419 '#type' => 'checkbox',
420 '#title' => t('Enable user tracking'),
421 '#description' => $description,
422 '#default_value' => isset($account->data['piwik']['custom']) ? $account->data['piwik']['custom'] : ($custom == 1),
430 * Implements hook_user_presave().
432 function piwik_user_presave(&$edit, $account, $category) {
433 if (isset($edit['piwik']['custom'])) {
434 $edit['data']['piwik']['custom'] = $edit['piwik']['custom'];
439 * Implements hook_cron().
441 function piwik_cron() {
442 // Regenerate the piwik.js every day.
443 if (REQUEST_TIME - variable_get('piwik_last_cache', 0) >= 86400 && variable_get('piwik_cache', 0)) {
444 _piwik_cache(variable_get('piwik_url_http', '') . 'piwik.js', TRUE);
445 variable_set('piwik_last_cache', REQUEST_TIME);
450 * Implements hook_preprocess_search_results().
452 * Collects and adds the number of search results to the head.
454 function piwik_preprocess_search_results(&$variables) {
455 // There is no search result $variable available that hold the number of items
456 // found. But the pager item mumber can tell the number of search results.
457 global $pager_total_items;
459 drupal_add_js('window.piwik_search_results = ' . intval($pager_total_items[0]) . ';', array('type' => 'inline', 'group' => JS_LIBRARY-1));
463 * Download/Synchronize/Cache tracking code file locally.
466 * The full URL to the external javascript file.
467 * @param $sync_cached_file
468 * Synchronize tracking code and update if remote file have changed.
470 * The path to the local javascript file on success, boolean FALSE on failure.
472 function _piwik_cache($location, $sync_cached_file = FALSE) {
473 $path = 'public://piwik';
474 $file_destination = $path . '/' . basename($location);
476 if (!file_exists($file_destination) || $sync_cached_file) {
477 // Download the latest tracking code.
478 $result = drupal_http_request($location);
480 if ($result->code == 200) {
481 if (file_exists($file_destination)) {
482 // Synchronize tracking code and and replace local file if outdated.
483 $data_hash_local = drupal_hash_base64(file_get_contents($file_destination));
484 $data_hash_remote = drupal_hash_base64($result->data);
485 // Check that the files directory is writable.
486 if ($data_hash_local != $data_hash_remote && file_prepare_directory($path)) {
487 // Save updated tracking code file to disk.
488 file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
489 watchdog('piwik', 'Locally cached tracking code file has been updated.', array(), WATCHDOG_INFO);
491 // Change query-strings on css/js files to enforce reload for all users.
492 _drupal_flush_css_js();
496 // Check that the files directory is writable.
497 if (file_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
498 // There is no need to flush JS here as core refreshes JS caches
499 // automatically, if new files are added.
500 file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
501 watchdog('piwik', 'Locally cached tracking code file has been saved.', array(), WATCHDOG_INFO);
503 // Return the local JS file path.
504 return file_create_url($file_destination);
510 // Return the local JS file path.
511 return file_create_url($file_destination);
516 * Delete cached files and directory.
518 function piwik_clear_js_cache() {
519 $path = 'public://piwik';
520 if (file_prepare_directory($path)) {
521 file_scan_directory($path, '/.*/', array('callback' => 'file_unmanaged_delete'));
524 // Change query-strings on css/js files to enforce reload for all users.
525 _drupal_flush_css_js();
527 watchdog('piwik', 'Local cache has been purged.', array(), WATCHDOG_INFO);
532 * Helper function for grabbing search keys. Function is missing in D7.
534 * http://api.drupal.org/api/function/search_get_keys/6
536 function piwik_search_get_keys() {
538 if (!isset($return)) {
539 // Extract keys as remainder of path
540 // Note: support old GET format of searches for existing links.
541 $path = explode('/', $_GET['q'], 3);
542 $keys = empty($_REQUEST['keys']) ? '' : $_REQUEST['keys'];
543 $return = count($path) == 3 ? $path[2] : $keys;
549 * Tracking visibility check for an user object.
552 * A user object containing an array of roles to check.
554 * A decision on if the current user is being tracked by Piwik.
556 function _piwik_visibility_user($account) {
560 // Is current user a member of a role that should be tracked?
561 if (_piwik_visibility_roles($account)) {
563 // Use the user's block visibility setting, if necessary.
564 if (($custom = variable_get('piwik_custom', 0)) != 0) {
565 if ($account->uid && isset($account->data['piwik']['custom'])) {
566 $enabled = $account->data['piwik']['custom'];
569 $enabled = ($custom == 1);
582 * Based on visibility setting this function returns TRUE if GA code should
583 * be added for the current role and otherwise FALSE.
585 function _piwik_visibility_roles($account) {
587 $visibility = variable_get('piwik_visibility_roles', 0);
588 $enabled = $visibility;
589 $roles = variable_get('piwik_roles', array());
591 if (array_sum($roles) > 0) {
592 // One or more roles are selected.
593 foreach (array_keys($account->roles) as $rid) {
594 // Is the current user a member of one of these roles?
595 if (isset($roles[$rid]) && $rid == $roles[$rid]) {
596 // Current user is a member of a role that should be tracked/excluded from tracking.
597 $enabled = !$visibility;
603 // No role is selected for tracking, therefore all roles should be tracked.
611 * Based on visibility setting this function returns TRUE if GA code should
612 * be added to the current page and otherwise FALSE.
614 function _piwik_visibility_pages() {
617 // Cache visibility setting in hook_init for hook_footer.
618 if (!isset($page_match)) {
620 $visibility = variable_get('piwik_visibility_pages', 0);
621 $setting_pages = variable_get('piwik_pages', PIWIK_PAGES);
623 // Match path if necessary.
624 if (!empty($setting_pages)) {
625 // Convert path to lowercase. This allows comparison of the same path
626 // with different case. Ex: /Page, /page, /PAGE.
627 $pages = drupal_strtolower($setting_pages);
628 if ($visibility < 2) {
629 // Convert the Drupal path to lowercase
630 $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
631 // Compare the lowercase internal and lowercase path alias (if any).
632 $page_match = drupal_match_path($path, $pages);
633 if ($path != $_GET['q']) {
634 $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
636 // When $visibility has a value of 0, the tracking code is displayed on
637 // all pages except those listed in $pages. When set to 1, it
638 // is displayed only on those pages listed in $pages.
639 $page_match = !($visibility xor $page_match);
641 elseif (module_exists('php')) {
642 $page_match = php_eval($setting_pages);
657 * Get the page titles trail for the current page.
659 * Based on menu_get_active_breadcrumb().
662 * All page titles, including current page.
664 function _piwik_get_hierarchy_titles() {
667 // No breadcrumb for the front page.
668 if (drupal_is_front_page()) {
672 $item = menu_get_item();
673 if (!empty($item['access'])) {
674 $active_trail = menu_get_active_trail();
676 // Allow modules to alter the breadcrumb, if possible, as that is much
677 // faster than rebuilding an entirely new active trail.
678 drupal_alter('menu_breadcrumb', $active_trail, $item);
680 // Remove the tab root (parent) if the current path links to its parent.
681 // Normally, the tab root link is included in the breadcrumb, as soon as we
682 // are on a local task or any other child link. However, if we are on a
683 // default local task (e.g., node/%/view), then we do not want the tab root
684 // link (e.g., node/%) to appear, as it would be identical to the current
685 // page. Since this behavior also needs to work recursively (i.e., on
686 // default local tasks of default local tasks), and since the last non-task
687 // link in the trail is used as page title (see menu_get_active_title()),
688 // this condition cannot be cleanly integrated into menu_get_active_trail().
689 // menu_get_active_trail() already skips all links that link to their parent
690 // (commonly MENU_DEFAULT_LOCAL_TASK). In order to also hide the parent link
691 // itself, we always remove the last link in the trail, if the current
692 // router item links to its parent.
693 if (($item['type'] & MENU_LINKS_TO_PARENT) == MENU_LINKS_TO_PARENT) {
694 array_pop($active_trail);
697 foreach ($active_trail as $parent) {
698 $titles[] = $parent['title'];