View source
<?php
define('PK_TRACKFILES_EXTENSIONS', '7z|aac|arc|arj|asf|asx|avi|bin|csv|doc|exe|flv|gif|gz|gzip|hqx|jar|jpe?g|js|mp(2|3|4|e?g)|mov(ie)?|msi|msp|pdf|phps|png|ppt|qtm?|ra(m|r)?|sea|sit|tar|tgz|torrent|txt|wav|wma|wmv|wpd|xls|xml|z|zip');
function piwik_help($section) {
switch ($section) {
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/',
));
}
}
function piwik_menu($maycache) {
global $user;
$items = array();
if ($maycache) {
$items[] = array(
'path' => 'admin/settings/piwik',
'title' => t('Piwik'),
'description' => t('Configure the settings used to generate your Piwik tracking code.'),
'callback' => 'drupal_get_form',
'callback arguments' => 'piwik_admin_settings_form',
'access' => user_access('administer piwik'),
'type' => MENU_NORMAL_ITEM,
);
}
else {
$id = variable_get('piwik_site_id', '');
if (!empty($id) && _piwik_visibility_pages() && _piwik_visibility_user($user)) {
$url_http = variable_get('piwik_url_http', '');
$url_https = variable_get('piwik_url_https', '');
$scope = variable_get('piwik_js_scope', 'footer');
$script = 'var pkBaseURL = (("https:" == document.location.protocol) ? "' . check_url($url_https) . '" : "' . check_url($url_http) . '");';
if (variable_get('piwik_cache', 0) && variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC && ($source = _piwik_cache($url_http . '/piwik.js'))) {
drupal_add_js($source, 'module', $scope);
}
else {
$script .= 'document.write(unescape("%3Cscript src=\'" + pkBaseURL + "/piwik.js\' type=\'text/javascript\'%3E%3C/script%3E"));';
}
drupal_add_js($script, 'inline', $scope);
}
}
return $items;
}
function piwik_perm() {
return array(
'administer piwik',
'opt-in or out of tracking',
'use PHP for tracking visibility',
);
}
function piwik_footer($main = 0) {
global $user;
$id = variable_get('piwik_site_id', '');
if (!empty($id) && _piwik_visibility_pages() && _piwik_visibility_user($user)) {
$piwik_vars = array();
$url_custom = '';
if (module_exists('search') && variable_get('piwik_site_search', FALSE) && arg(0) == 'search' && ($keys = search_get_keys())) {
$url_custom = drupal_to_js(url('search', 'query=' . $keys));
}
if (function_exists('drupal_get_headers')) {
$headers = drupal_get_headers();
if (strstr($headers, 'HTTP/1.1 403 Forbidden')) {
$url_custom = '"/403/URL=" + document.location.pathname + document.location.search + "/From=" + document.referrer';
}
elseif (strstr($headers, 'HTTP/1.1 404 Not Found')) {
$url_custom = '"/404/URL=" + document.location.pathname + document.location.search + "/From=" + document.referrer';
}
}
$codesnippet_before = variable_get('piwik_codesnippet_before', '');
$codesnippet_after = variable_get('piwik_codesnippet_after', '');
$script = 'try {';
$script .= 'var piwikTracker = Piwik.getTracker(pkBaseURL + "/piwik.php", ' . drupal_to_js(variable_get('piwik_site_id', '')) . ');';
if (!empty($url_custom)) {
$script .= 'piwikTracker.setDocumentTitle(' . $url_custom . ');';
}
if (variable_get('piwik_track', 1) && !(variable_get('piwik_trackfiles_extensions', PK_TRACKFILES_EXTENSIONS) == PK_TRACKFILES_EXTENSIONS)) {
$script .= 'piwikTracker.setDownloadExtensions(' . drupal_to_js(variable_get('piwik_trackfiles_extensions', PK_TRACKFILES_EXTENSIONS)) . ');';
}
if (!empty($piwik_vars)) {
$piwik_vars_fields = array();
foreach ($piwik_vars as $name => $value) {
$piwik_vars_fields[] = drupal_to_js($name) . ':' . drupal_to_js($value);
}
if (count($piwik_vars_fields) > 0) {
$script .= 'piwikTracker.setCustomVars({ ' . implode(', ', $piwik_vars_fields) . ' });';
}
}
if (!empty($codesnippet_before)) {
$script .= $codesnippet_before;
}
$script .= 'piwikTracker.trackPageView();';
if (variable_get('piwik_track', 1)) {
$script .= 'piwikTracker.enableLinkTracking();';
}
if (!empty($codesnippet_after)) {
$script .= $codesnippet_after;
}
$script .= '} catch(err) {}';
drupal_add_js($script, 'inline', 'footer');
}
}
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;
}
}
function piwik_admin_settings_form() {
$form['account'] = array(
'#type' => 'fieldset',
'#title' => t('General settings'),
'#collapsible' => FALSE,
);
$form['account']['piwik_site_id'] = array(
'#type' => 'textfield',
'#title' => t('Piwik site ID'),
'#default_value' => variable_get('piwik_site_id', ''),
'#size' => 15,
'#maxlength' => 20,
'#required' => TRUE,
'#description' => t('The user account number is unique to the websites domain. Click the <strong>Settings</strong> link in your Piwik account, then the <strong>Sites</strong> tab and enter the <strong>ID</strong> into this field.'),
);
$form['account']['piwik_url_http'] = array(
'#type' => 'textfield',
'#title' => t('Piwik HTTP URL'),
'#default_value' => variable_get('piwik_url_http', ''),
'#size' => 80,
'#maxlength' => 255,
'#required' => TRUE,
'#description' => t('The URL to your Piwik base directory. Example: "http://www.example.com/piwik".'),
);
$form['account']['piwik_url_https'] = array(
'#type' => 'textfield',
'#title' => t('Piwik HTTPS URL'),
'#default_value' => variable_get('piwik_url_https', ''),
'#size' => 80,
'#maxlength' => 255,
'#description' => t('The URL to your Piwik base directory with SSL certificate installed. Required if you track a SSL enabled website. Example: "https://www.example.com/piwik".'),
);
$form['user_vis_settings'] = array(
'#type' => 'fieldset',
'#title' => t('User specific tracking settings'),
'#collapsible' => TRUE,
);
$form['user_vis_settings']['piwik_custom'] = array(
'#type' => 'radios',
'#title' => t('Custom tracking settings'),
'#options' => array(
t('Users cannot control whether they are tracked or not.'),
t('Track users by default, but let individual users to opt out.'),
t('Do not track users by default, but let individual users to opt in.'),
),
'#description' => t('Allow individual users to customize the visibility of tracking in their account settings. Only users with %permission permission are allowed to set their own preference.', array(
'%permission' => t('opt-in or out of tracking'),
)),
'#default_value' => variable_get('piwik_custom', 0),
);
$form['role_vis_settings'] = array(
'#type' => 'fieldset',
'#title' => t('Role specific tracking settings'),
'#collapsible' => TRUE,
);
$default_role_options = array();
$default_roles = variable_get('piwik_roles', array());
foreach ($default_roles as $default_rid => $checked) {
if ($checked) {
$default_role_options[] = $default_rid;
}
}
$roles = _piwik_user_roles();
$role_options = array();
foreach ($roles as $rid => $name) {
$role_options[$rid] = $name;
}
$form['role_vis_settings']['piwik_roles'] = array(
'#type' => 'checkboxes',
'#title' => t('Add tracking for specific roles'),
'#default_value' => $default_role_options,
'#options' => $role_options,
'#description' => t('Add tracking only for the selected role(s). If none of the roles are selected, all users will be tracked. If a user has any of the roles checked, that user will be tracked.'),
);
$form['page_vis_settings'] = array(
'#type' => 'fieldset',
'#title' => t('Page specific tracking settings'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$access = user_access('use PHP for tracking visibility');
$visibility = variable_get('piwik_visibility', 0);
$pages = variable_get('piwik_pages', '');
if ($visibility == 2 && !$access) {
$form['page_vis_settings'] = array();
$form['page_vis_settings']['visibility'] = array(
'#type' => 'value',
'#value' => 2,
);
$form['page_vis_settings']['pages'] = array(
'#type' => 'value',
'#value' => $pages,
);
}
else {
$options = array(
t('Add to every page except the listed pages.'),
t('Add to the listed pages only.'),
);
$description = t("Enter one page per line as Drupal paths. The '*' character is a wildcard. Example paths are %blog for the blog page and %blog-wildcard for every personal blog. %front is the front page.", array(
'%blog' => 'blog',
'%blog-wildcard' => 'blog/*',
'%front' => '<front>',
));
if ($access) {
$options[] = t('Add if the following PHP code returns <code>TRUE</code> (PHP-mode, experts only).');
$description .= ' ' . t('If the PHP-mode is chosen, enter PHP code between %php. Note that executing incorrect PHP-code can break your Drupal site.', array(
'%php' => '<?php ?>',
));
}
$form['page_vis_settings']['piwik_visibility'] = array(
'#type' => 'radios',
'#title' => t('Add tracking to specific pages'),
'#options' => $options,
'#default_value' => $visibility,
);
$form['page_vis_settings']['piwik_pages'] = array(
'#type' => 'textarea',
'#title' => t('Pages'),
'#default_value' => $pages,
'#description' => $description,
'#wysiwyg' => FALSE,
);
}
$form['linktracking'] = array(
'#type' => 'fieldset',
'#title' => t('Link tracking settings'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$form['linktracking']['piwik_track'] = array(
'#type' => 'checkbox',
'#title' => t('Track download and outgoing links'),
'#default_value' => variable_get('piwik_track', 1),
'#description' => t('Enables tracking of clicks on download and outgoing links.'),
);
$form['linktracking']['piwik_trackfiles_extensions'] = array(
'#type' => 'textfield',
'#title' => t('File extensions to track'),
'#default_value' => variable_get('piwik_trackfiles_extensions', PK_TRACKFILES_EXTENSIONS),
'#description' => t('A pipe separated list of file extensions that should be tracked when clicked with regular expression support. Example: !extensions', array(
'!extensions' => PK_TRACKFILES_EXTENSIONS,
)),
'#maxlength' => 255,
);
$form['advanced'] = array(
'#type' => 'fieldset',
'#title' => t('Advanced settings'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
);
$form['advanced']['piwik_cache'] = array(
'#type' => 'checkbox',
'#title' => t('Cache tracking code file locally'),
'#description' => t("If checked, the tracking code file is retrieved from Piwik and cached locally. It is updated daily from your Piwik servers to ensure updates to tracking code are reflected in the local copy."),
'#default_value' => variable_get('piwik_cache', 0),
);
if (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PRIVATE) {
$form['advanced']['piwik_cache']['#disabled'] = TRUE;
$form['advanced']['piwik_cache']['#description'] .= ' ' . t('<a href="@url">Public file transfers</a> must be enabled to allow local caching.', array(
'@url' => url('admin/settings/file-system', array(
'query' => drupal_get_destination(),
)),
));
}
$site_search_dependencies = '<div class="admin-dependencies">';
$site_search_dependencies .= t('Depends on: !dependencies', array(
'!dependencies' => module_exists('search') ? t('@module (<span class="admin-enabled">enabled</span>)', array(
'@module' => 'Search',
)) : t('@module (<span class="admin-disabled">disabled</span>)', array(
'@module' => 'Search',
)),
));
$site_search_dependencies .= '</div>';
$form['advanced']['piwik_site_search'] = array(
'#type' => 'checkbox',
'#title' => t('Track internal search') . ' (EXPERIMENTAL)',
'#description' => t('If checked, internal search keywords are tracked. You must manually install and configure the Site Search plugin for your sites. For the setting <em>Search URL</em> use a value of <strong>search</strong> and for <em>Search Parameter</em> use a value of <strong>query</strong>. For more information see <a href="@url">SiteSearch plugin for piwik</a>.', array(
'@url' => 'http://github.com/BeezyT/piwik-sitesearch/wiki',
)) . $site_search_dependencies,
'#default_value' => variable_get('piwik_site_search', FALSE),
'#disabled' => module_exists('search') ? FALSE : TRUE,
);
$form['advanced']['codesnippet'] = array(
'#type' => 'fieldset',
'#title' => t('Custom JavaScript code'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#description' => t('You can add custom Piwik <a href="@snippets">code snippets</a> here. These will be added to every page that Piwik appears on. <strong>Do not include the <script> tags</strong>, and always end your code with a semicolon (;).', array(
'@snippets' => 'http://piwik.org/docs/javascript-tracking/',
)),
);
$form['advanced']['codesnippet']['piwik_codesnippet_before'] = array(
'#type' => 'textarea',
'#title' => t('Code snippet (before)'),
'#default_value' => variable_get('piwik_codesnippet_before', ''),
'#rows' => 5,
'#wysiwyg' => FALSE,
'#description' => t('Code in this textarea will be added <strong>before</strong> piwikTracker.trackPageView().'),
);
$form['advanced']['codesnippet']['piwik_codesnippet_after'] = array(
'#type' => 'textarea',
'#title' => t('Code snippet (after)'),
'#default_value' => variable_get('piwik_codesnippet_after', ''),
'#rows' => 5,
'#wysiwyg' => FALSE,
'#description' => t("Code in this textarea will be added <strong>after</strong> piwikTracker.trackPageView(). This is useful if you'd like to track a site in two accounts."),
);
$form['advanced']['piwik_js_scope'] = array(
'#type' => 'select',
'#title' => t('JavaScript scope'),
'#description' => t("<strong>Warning:</strong> Adding the external JavaScript files to the footer region is recommended for performance reasons."),
'#options' => array(
'footer' => t('Footer'),
'header' => t('Header'),
),
'#default_value' => variable_get('piwik_js_scope', 'footer'),
);
return system_settings_form($form);
}
function piwik_admin_settings_form_validate($form_id, $form_values) {
if (!preg_match('/^\\d{1,}$/', $form_values['piwik_site_id'])) {
form_set_error('piwik_site_id', t('A valid Piwik site ID is an integer only.'));
}
$url = $form_values['piwik_url_http'] . '/piwik.php';
$result = drupal_http_request($url);
if ($result->code != 200) {
form_set_error('piwik_url_http', t('The validation of "@url" failed with error "@error" (HTTP code @code).', array(
'@url' => check_url($url),
'@error' => $result->error,
'@code' => $result->code,
)));
}
if (!empty($form_values['piwik_url_https'])) {
$url = $form_values['piwik_url_https'] . '/piwik.php';
$result = drupal_http_request($url);
if ($result->code != 200) {
form_set_error('piwik_url_https', t('The validation of "@url" failed with error "@error" (HTTP code @code).', array(
'@url' => check_url($url),
'@error' => $result->error,
'@code' => $result->code,
)));
}
}
if (preg_match('/(.*)<\\/?script(.*)>(.*)/i', $form_values['piwik_codesnippet_before'])) {
form_set_error('piwik_codesnippet_before', t('Do not include the <script> tags in the javascript code snippets.'));
}
if (preg_match('/(.*)<\\/?script(.*)>(.*)/i', $form_values['piwik_codesnippet_after'])) {
form_set_error('piwik_codesnippet_after', t('Do not include the <script> tags in the javascript code snippets.'));
}
}
function piwik_admin_settings_form_submit($form_id, $form_values) {
$form_values['piwik_pages'] = trim($form_values['piwik_pages']);
$form_values['piwik_codesnippet_before'] = trim($form_values['piwik_codesnippet_before']);
$form_values['piwik_codesnippet_after'] = trim($form_values['piwik_codesnippet_after']);
system_settings_form_submit($form_id, $form_values);
}
function piwik_cron() {
if (time() - variable_get('piwik_last_cache', 0) >= 86400) {
file_delete(file_directory_path() . '/piwik/piwik.js');
variable_set('piwik_last_cache', time());
}
}
function _piwik_cache($location) {
$directory = file_directory_path() . '/piwik';
$file_destination = $directory . '/' . basename($location);
if (!file_exists($file_destination)) {
$result = drupal_http_request($location);
if ($result->code == 200) {
if (file_check_directory($directory, FILE_CREATE_DIRECTORY)) {
return file_save_data($result->data, $directory . '/' . basename($location), FILE_EXISTS_REPLACE);
}
}
}
else {
return $file_destination;
}
}
function _piwik_visibility_user($account) {
$enabled = FALSE;
if (_piwik_visibility_roles($account)) {
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;
}
function _piwik_visibility_roles($account) {
$enabled = FALSE;
$roles = variable_get('piwik_roles', array());
if (array_sum($roles) > 0) {
foreach (array_keys($account->roles) as $rid) {
if (isset($roles[$rid]) && $rid == $roles[$rid]) {
$enabled = TRUE;
break;
}
}
}
else {
$enabled = TRUE;
}
return $enabled;
}
function _piwik_visibility_pages() {
$visibility = variable_get('piwik_visibility', 0);
$pages = variable_get('piwik_pages', '');
if (!empty($pages)) {
if ($visibility < 2) {
$path = drupal_get_path_alias($_GET['q']);
$page_match = _piwik_match_path($path, $pages);
if ($path != $_GET['q']) {
$page_match = $page_match || _piwik_match_path($_GET['q'], $pages);
}
$page_match = !($visibility xor $page_match);
}
else {
$page_match = drupal_eval($pages);
}
}
else {
$page_match = TRUE;
}
return $page_match;
}
function _piwik_match_path($path, $patterns) {
static $regexps;
if (!isset($regexps[$patterns])) {
$regexps[$patterns] = '/^(' . preg_replace(array(
'/(\\r\\n?|\\n)/',
'/\\\\\\*/',
'/(^|\\|)\\\\<front\\\\>($|\\|)/',
), array(
'|',
'.*',
'\\1' . preg_quote(variable_get('site_frontpage', 'node'), '/') . '\\2',
), preg_quote($patterns, '/')) . ')$/';
}
return preg_match($regexps[$patterns], $path);
}
function _piwik_user_roles() {
$roles = array(
DRUPAL_ANONYMOUS_RID => NULL,
DRUPAL_AUTHENTICATED_RID => NULL,
);
$result = db_query('SELECT * FROM {role} ORDER BY name');
while ($role = db_fetch_object($result)) {
switch ($role->rid) {
case DRUPAL_ANONYMOUS_RID:
$roles[$role->rid] = t($role->name);
break;
case DRUPAL_AUTHENTICATED_RID:
$roles[$role->rid] = t($role->name);
break;
default:
$roles[$role->rid] = $role->name;
}
}
return array_filter($roles);
}