statcounter.module in StatCounter 7.2
Same filename and directory in other branches
Drupal Module: Statcounter Adds the required Javascript to the bottom of all your Drupal pages to allow tracking by the Statcounter statistics service.
Based on the Google Analytics module <http://drupal.org/project/piwik> and Piwik Web analytics module <http://drupal.org/project/piwik> by Alexander Hass <http://drupal.org/user/85918>
@author: kdebaas <http://drupal.org/user/75900>
File
statcounter.moduleView source
<?php
/**
* @file
* Drupal Module: Statcounter
* Adds the required Javascript to the bottom of all your Drupal pages
* to allow tracking by the Statcounter statistics service.
*
* Based on the Google Analytics module <http://drupal.org/project/piwik>
* and Piwik Web analytics module <http://drupal.org/project/piwik>
* by Alexander Hass <http://drupal.org/user/85918>
*
* @author: kdebaas <http://drupal.org/user/75900>
*/
/**
* Implements hook_help().
*
* Displays help and module information.
*
* @param path
* Which path of the site we're using to display help
* @param arg
* Array that holds the current path as returned from arg() function
*/
function statcounter_help($path, $arg) {
switch ($path) {
case 'admin/config/system/statcounter':
return t('<a href="@sc_url">Statcounter</a>, a free and invisible web tracker, hit counter and real-time detailed web stats.', array(
'@sc_url' => 'http://www.statcounter.com/',
));
}
}
/**
* Implements hook_permission().
*/
function statcounter_permission() {
return array(
'administer statcounter' => array(
'title' => t('Administer Statcounter'),
'description' => t('Perform maintenance tasks for Statcounter.'),
),
'opt-in or out of tracking' => array(
'title' => t('Opt-in or out of tracking'),
'description' => t('Allow users to decide if tracking code will be added to pages or not.'),
),
'use PHP for tracking visibility' => array(
'title' => t('Use PHP for tracking visibility'),
'description' => t('Enter PHP code in the field for tracking visibility settings. %warning', array(
'%warning' => t('Warning: Give to trusted roles only; this permission has security implications.'),
)),
),
);
}
/**
* Implements hook_menu().
*/
function statcounter_menu() {
$items['admin/config/system/statcounter'] = array(
'title' => 'Statcounter',
'description' => 'Configure the settings used to generate your Statcounter tracking code.',
'page callback' => 'drupal_get_form',
'page arguments' => array(
'statcounter_admin_settings_form',
),
'access arguments' => array(
'administer statcounter',
),
'type' => MENU_NORMAL_ITEM,
'file' => 'statcounter.admin.inc',
);
return $items;
}
/**
* Implements hook_page_alter() to insert JavaScript to the appropriate scope/region of the page.
*/
function statcounter_page_alter(&$page) {
global $user;
$id = variable_get('statcounter_project_id', '');
$security_code = variable_get('statcounter_security_code', '');
$invisibility = variable_get('statcounter_invisible_tracking', 1);
// Get page status code for visibility filtering.
$status = drupal_get_http_header('Status');
$trackable_status_codes = array(
'403 Forbidden',
'404 Not Found',
);
// 1. Check if the statcounter 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 (!empty($id) && (_statcounter_visibility_pages() || in_array($status, $trackable_status_codes)) && _statcounter_visibility_user($user)) {
$scope = variable_get('statcounter_js_scope', 'footer');
// Build tracker code.
$inline_script = 'var sc_project=' . $id . ';';
$inline_script .= 'var sc_invisible=' . $invisibility . ';';
$inline_script .= 'var sc_security="' . $security_code . '";';
// Should a local cached copy of the tracking code be used?
if (variable_get('statcounter_cache', 0) && ($url = _statcounter_cache('http://www.statcounter.com/counter/counter_xhtml.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 = '?' . variable_get('css_js_query_string', '0');
$file = $url . $query_string;
$type = 'file';
}
else {
$file = 'http://www.statcounter.com/counter/counter_xhtml.js';
$type = 'external';
}
// Add tracker code to chosen region. We do not use drupal_add_js() here,
// because it doesn't support regions as scope.
$page[$scope]['statcounter']['first'] = array(
'#markup' => $inline_script,
'#prefix' => '<script type="text/javascript">',
'#suffix' => '</script>',
);
$page[$scope]['statcounter']['second'] = array(
'#markup' => "<script type=\"text/javascript\" src=\"{$file}\"></script>",
);
$page[$scope]['statcounter']['third'] = array(
'#markup' => '<img class="statcounter" src="http://c.statcounter.com/' . $id . '/0/' . $security_code . '/' . $invisibility . '/" alt="drupal statistics" />',
'#prefix' => '<noscript><div class="statcounter"><a title="drupal statistics" href="http://statcounter.com/drupal/">',
'#suffix' => '</a></div></noscript>',
);
}
}
/**
* Implement hook_form_FORM_ID_alter().
*
* Allow users to decide if tracking code will be added to pages or not.
*/
function statcounter_form_user_profile_form_alter(&$form, &$form_state) {
$account = $form['#user'];
$category = $form['#user_category'];
if ($category == 'account' && user_access('opt-in or out of tracking') && ($custom = variable_get('statcounter_custom', 0)) != 0 && _statcounter_visibility_roles($account)) {
$form['statcounter'] = array(
'#type' => 'fieldset',
'#title' => t('Statcounter 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['statcounter']['custom'] = array(
'#type' => 'checkbox',
'#title' => t('Enable user tracking'),
'#description' => $description,
'#default_value' => isset($account->data['statcounter']['custom']) ? $account->data['statcounter']['custom'] : $custom == 1,
);
return $form;
}
}
/**
* Implements hook_user_presave().
*/
function statcounter_user_presave(&$edit, $account, $category) {
if (isset($edit['statcounter']['custom'])) {
$edit['data']['statcounter']['custom'] = $edit['statcounter']['custom'];
}
}
/**
* Implements hook_cron().
*/
function statcounter_cron() {
// Regenerate the statcounter.js every day.
if (REQUEST_TIME - variable_get('statcounter_last_cache', 0) >= 86400 && variable_get('statcounter_cache', 0)) {
_statcounter_cache('http://www.statcounter.com/counter/counter.js', TRUE);
variable_set('statcounter_last_cache', REQUEST_TIME);
}
}
/**
* 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 _statcounter_cache($location, $sync_cached_file = FALSE) {
$path = 'public://statcounter';
$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 = drupal_hash_base64(file_get_contents($file_destination));
$data_hash_remote = drupal_hash_base64($result->data);
// Check that the files directory is writable.
if ($data_hash_local != $data_hash_remote && file_prepare_directory($path)) {
// Save updated tracking code file to disk.
file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
watchdog('statcounter', '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_prepare_directory($path, FILE_CREATE_DIRECTORY)) {
// There is no need to flush JS here as core refreshes JS caches
// automatically, if new files are added.
file_unmanaged_save_data($result->data, $file_destination, FILE_EXISTS_REPLACE);
watchdog('statcounter', 'Locally cached tracking code file has been saved.', array(), WATCHDOG_INFO);
// Return the local JS file path.
return file_create_url($file_destination);
}
}
}
}
else {
// Return the local JS file path.
return file_create_url($file_destination);
}
}
/**
* Delete cached files and directory.
*/
function statcounter_clear_js_cache() {
$path = 'public://statcounter';
if (file_prepare_directory($path)) {
file_scan_directory($path, '/.*/', array(
'callback' => 'file_unmanaged_delete',
));
drupal_rmdir($path);
// Change query-strings on css/js files to enforce reload for all users.
_drupal_flush_css_js();
watchdog('statcounter', '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 Statcounter.
*/
function _statcounter_visibility_user($account) {
$enabled = FALSE;
// Is current user a member of a role that should be tracked?
if (_statcounter_visibility_header($account) && _statcounter_visibility_roles($account)) {
// Use the user's block visibility setting, if necessary.
if (($custom = variable_get('statcounter_custom', 0)) != 0) {
if ($account->uid && isset($account->data['statcounter']['custom'])) {
$enabled = $account->data['statcounter']['custom'];
}
else {
$enabled = $custom == 1;
}
}
else {
$enabled = TRUE;
}
}
return $enabled;
}
/**
* Based on visibility setting this function returns TRUE if Statcounter code should
* be added for the current role and otherwise FALSE.
*/
function _statcounter_visibility_roles($account) {
$visibility = variable_get('statcounter_visibility_roles', 0);
$enabled = $visibility;
$roles = variable_get('statcounter_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 Statcounter code should
* be added to the current page and otherwise FALSE.
*/
function _statcounter_visibility_pages() {
static $page_match;
// Cache visibility setting in hook_init for hook_footer.
if (!isset($page_match)) {
$visibility = variable_get('statcounter_visibility_pages', 0);
$setting_pages = variable_get('statcounter_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);
}
elseif (module_exists('php')) {
$page_match = php_eval($setting_pages);
}
else {
$page_match = FALSE;
}
}
else {
$page_match = TRUE;
}
}
return $page_match;
}
/**
* Based on headers send by clients this function returns TRUE if Statcounter code should
* be added to the current page and otherwise FALSE.
*/
function _statcounter_visibility_header($account) {
if (($account->uid || variable_get('cache', 0) == 0) && variable_get('statcounter_privacy_donottrack', 1) && !empty($_SERVER['HTTP_DNT'])) {
// Disable tracking if caching is disabled or a visitors is logged in and
// have opted out from tracking via DNT (Do-Not-Track) header.
return FALSE;
}
return TRUE;
}
Functions
Name![]() |
Description |
---|---|
statcounter_clear_js_cache | Delete cached files and directory. |
statcounter_cron | Implements hook_cron(). |
statcounter_form_user_profile_form_alter | Implement hook_form_FORM_ID_alter(). |
statcounter_help | Implements hook_help(). |
statcounter_menu | Implements hook_menu(). |
statcounter_page_alter | Implements hook_page_alter() to insert JavaScript to the appropriate scope/region of the page. |
statcounter_permission | Implements hook_permission(). |
statcounter_user_presave | Implements hook_user_presave(). |
_statcounter_cache | Download/Synchronize/Cache tracking code file locally. |
_statcounter_visibility_header | Based on headers send by clients this function returns TRUE if Statcounter code should be added to the current page and otherwise FALSE. |
_statcounter_visibility_pages | Based on visibility setting this function returns TRUE if Statcounter code should be added to the current page and otherwise FALSE. |
_statcounter_visibility_roles | Based on visibility setting this function returns TRUE if Statcounter code should be added for the current role and otherwise FALSE. |
_statcounter_visibility_user | Tracking visibility check for an user object. |