updated plugin Connect Matomo version 1.0.30

This commit is contained in:
2023-10-22 22:21:31 +00:00
committed by Gitium
parent 9e3fa792d7
commit 959829cf69
24 changed files with 3619 additions and 3462 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,112 +1,112 @@
<?php
namespace WP_Piwik\Admin;
if (! class_exists ( 'WP_List_Table' ))
require_once (ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
class Sitebrowser extends \WP_List_Table {
private $data = array (), $wpPiwik;
public function __construct($wpPiwik) {
$this->wpPiwik = $wpPiwik;
if( isset($_POST['s']) ){
$cnt = $this->prepare_items ($_POST['s']);
} else {
$cnt = $this->prepare_items ();
}
global $status, $page;
$this->showSearchForm();
parent::__construct ( array (
'singular' => __ ( 'site', 'wp-piwik' ),
'plural' => __ ( 'sites', 'wp-piwik' ),
'ajax' => false
) );
if ($cnt > 0)
$this->display ();
else
echo '<p>' . __ ( 'No site configured yet.', 'wp-piwik' ) . '</p>';
}
public function get_columns() {
$columns = array (
'id' => __ ( 'Blog ID', 'wp-piwik' ),
'name' => __ ( 'Title', 'wp-piwik' ),
'siteurl' => __ ( 'URL', 'wp-piwik' ),
'piwikid' => __ ( 'Site ID (Piwik)', 'wp-piwik' )
);
return $columns;
}
public function prepare_items($search = '') {
$current_page = $this->get_pagenum ();
$per_page = 10;
global $blog_id;
global $wpdb;
global $pagenow;
if (is_plugin_active_for_network ( 'wp-piwik/wp-piwik.php' )) {
$total_items = $wpdb->get_var ( $wpdb->prepare('SELECT COUNT(*) FROM ' . $wpdb->blogs . ' WHERE CONCAT(domain, path) LIKE "%%%s%%" AND spam = 0 AND deleted = 0', $search));
$blogs = \WP_Piwik\Settings::getBlogList($per_page, $current_page, $search);
foreach ( $blogs as $blog ) {
$blogDetails = get_blog_details ( $blog['blog_id'], true );
$this->data [] = array (
'name' => $blogDetails->blogname,
'id' => $blogDetails->blog_id,
'siteurl' => $blogDetails->siteurl,
'piwikid' => $this->wpPiwik->getPiwikSiteId ( $blogDetails->blog_id )
);
}
} else {
$blogDetails = get_bloginfo ();
$this->data [] = array (
'name' => get_bloginfo ( 'name' ),
'id' => '-',
'siteurl' => get_bloginfo ( 'url' ),
'piwikid' => $this->wpPiwik->getPiwikSiteId ()
);
$total_items = 1;
}
$columns = $this->get_columns ();
$hidden = array ();
$sortable = array ();
$this->_column_headers = array (
$columns,
$hidden,
$sortable
);
$this->set_pagination_args ( array (
'total_items' => $total_items,
'per_page' => $per_page
) );
foreach ( $this->data as $key => $dataset ) {
if (empty ( $dataset ['piwikid'] ) || $dataset ['piwikid'] == 'n/a')
$this->data [$key] ['piwikid'] = __ ( 'Site not created yet.', 'wp-piwik' );
if ($this->wpPiwik->isNetworkMode ())
$this->data [$key] ['name'] = '<a href="index.php?page=wp-piwik_stats&wpmu_show_stats=' . $dataset ['id'] . '">' . $dataset ['name'] . '</a>';
}
$this->items = $this->data;
return count ( $this->items );
}
public function column_default($item, $column_name) {
switch ($column_name) {
case 'id' :
case 'name' :
case 'siteurl' :
case 'piwikid' :
return $item [$column_name];
default :
return print_r ( $item, true );
}
}
private function showSearchForm() {
?>
<form method="post">
<input type="hidden" name="page" value="<?php echo filter_var($_REQUEST['page'], FILTER_SANITIZE_STRING) ?>" />
<?php $this->search_box('Search domain and path', 'wpPiwikSiteSearch'); ?>
</form>
<?php
}
<?php
namespace WP_Piwik\Admin;
if (! class_exists ( 'WP_List_Table' ))
require_once (ABSPATH . 'wp-admin/includes/class-wp-list-table.php');
class Sitebrowser extends \WP_List_Table {
private $data = array (), $wpPiwik;
public function __construct($wpPiwik) {
$this->wpPiwik = $wpPiwik;
if( isset($_POST['s']) ){
$cnt = $this->prepare_items ($_POST['s']);
} else {
$cnt = $this->prepare_items ();
}
global $status, $page;
$this->showSearchForm();
parent::__construct ( array (
'singular' => __ ( 'site', 'wp-piwik' ),
'plural' => __ ( 'sites', 'wp-piwik' ),
'ajax' => false
) );
if ($cnt > 0)
$this->display ();
else
echo '<p>' . __ ( 'No site configured yet.', 'wp-piwik' ) . '</p>';
}
public function get_columns() {
$columns = array (
'id' => __ ( 'Blog ID', 'wp-piwik' ),
'name' => __ ( 'Title', 'wp-piwik' ),
'siteurl' => __ ( 'URL', 'wp-piwik' ),
'piwikid' => __ ( 'Site ID (Piwik)', 'wp-piwik' )
);
return $columns;
}
public function prepare_items($search = '') {
$current_page = $this->get_pagenum ();
$per_page = 10;
global $blog_id;
global $wpdb;
global $pagenow;
if (is_plugin_active_for_network ( 'wp-piwik/wp-piwik.php' )) {
$total_items = $wpdb->get_var ( $wpdb->prepare('SELECT COUNT(*) FROM ' . $wpdb->blogs . ' WHERE CONCAT(domain, path) LIKE "%%%s%%" AND spam = 0 AND deleted = 0', $search));
$blogs = \WP_Piwik\Settings::getBlogList($per_page, $current_page, $search);
foreach ( $blogs as $blog ) {
$blogDetails = get_blog_details ( $blog['blog_id'], true );
$this->data [] = array (
'name' => $blogDetails->blogname,
'id' => $blogDetails->blog_id,
'siteurl' => $blogDetails->siteurl,
'piwikid' => $this->wpPiwik->getPiwikSiteId ( $blogDetails->blog_id )
);
}
} else {
$blogDetails = get_bloginfo ();
$this->data [] = array (
'name' => get_bloginfo ( 'name' ),
'id' => '-',
'siteurl' => get_bloginfo ( 'url' ),
'piwikid' => $this->wpPiwik->getPiwikSiteId ()
);
$total_items = 1;
}
$columns = $this->get_columns ();
$hidden = array ();
$sortable = array ();
$this->_column_headers = array (
$columns,
$hidden,
$sortable
);
$this->set_pagination_args ( array (
'total_items' => $total_items,
'per_page' => $per_page
) );
foreach ( $this->data as $key => $dataset ) {
if (empty ( $dataset ['piwikid'] ) || $dataset ['piwikid'] == 'n/a')
$this->data [$key] ['piwikid'] = __ ( 'Site not created yet.', 'wp-piwik' );
if ($this->wpPiwik->isNetworkMode ())
$this->data [$key] ['name'] = '<a href="index.php?page=wp-piwik_stats&wpmu_show_stats=' . $dataset ['id'] . '">' . $dataset ['name'] . '</a>';
}
$this->items = $this->data;
return count ( $this->items );
}
public function column_default($item, $column_name) {
switch ($column_name) {
case 'id' :
case 'name' :
case 'siteurl' :
case 'piwikid' :
return $item [$column_name];
default :
return print_r ( $item, true );
}
}
private function showSearchForm() {
?>
<form method="post">
<input type="hidden" name="page" value="<?php echo filter_var($_REQUEST['page'], FILTER_SANITIZE_STRING) ?>" />
<?php $this->search_box('Search domain and path', 'wpPiwikSiteSearch'); ?>
</form>
<?php
}
}

View File

@ -52,4 +52,13 @@
self::$debug[$id] = array ( $params.'&token_auth=...' );
return $result;
}
public function reset() {
if (class_exists('\Piwik\Application\Environment') && !self::$piwikEnvironment) {
self::$piwikEnvironment->destroy();
}
if (class_exists('Piwik\FrontController'))
\Piwik\FrontController::unsetInstance();
parent::reset();
}
}

View File

@ -1,427 +1,427 @@
<?php
namespace WP_Piwik;
/**
* Manage WP-Piwik settings
*
* @author Andr&eacute; Br&auml;kling
* @package WP_Piwik
*/
class Settings {
/**
*
* @var Environment variables and default settings container
*/
private static $wpPiwik, $defaultSettings;
/**
*
* @var Define callback functions for changed settings
*/
private $checkSettings = array (
'piwik_url' => 'checkPiwikUrl',
'piwik_token' => 'checkPiwikToken',
'site_id' => 'requestPiwikSiteID',
'tracking_code' => 'prepareTrackingCode',
'noscript_code' => 'prepareNocscriptCode'
);
/**
*
* @var Register default configuration set
*/
private $globalSettings = array (
// Plugin settings
'revision' => 0,
'last_settings_update' => 0,
// User settings: Piwik configuration
'piwik_mode' => 'http',
'piwik_url' => '',
'piwik_path' => '',
'piwik_user' => '',
'matomo_user' => '',
'piwik_token' => '',
'auto_site_config' => true,
// User settings: Stats configuration
'default_date' => 'yesterday',
'stats_seo' => false,
'stats_ecommerce' => false,
'dashboard_widget' => false,
'dashboard_ecommerce' => false,
'dashboard_chart' => false,
'dashboard_seo' => false,
'toolbar' => false,
'capability_read_stats' => array (
'administrator' => true
),
'perpost_stats' => "disabled",
'plugin_display_name' => 'WP-Matomo',
'piwik_shortcut' => false,
'shortcodes' => false,
// User settings: Tracking configuration
'track_mode' => 'disabled',
'track_codeposition' => 'footer',
'track_noscript' => false,
'track_nojavascript' => false,
'proxy_url' => '',
'track_content' => 'disabled',
'track_search' => false,
'track_404' => false,
'add_post_annotations' => array(),
'add_customvars_box' => false,
'add_download_extensions' => '',
'set_download_extensions' => '',
'set_link_classes' => '',
'set_download_classes' => '',
'require_consent' => 'disabled',
'disable_cookies' => false,
'limit_cookies' => false,
'limit_cookies_visitor' => 34186669, // Piwik default 13 months
'limit_cookies_session' => 1800, // Piwik default 30 minutes
'limit_cookies_referral' => 15778463, // Piwik default 6 months
'track_admin' => false,
'capability_stealth' => array (),
'track_across' => false,
'track_across_alias' => false,
'track_crossdomain_linking' => false,
'track_feed' => false,
'track_feed_addcampaign' => false,
'track_feed_campaign' => 'feed',
'track_heartbeat' => 0,
'track_user_id' => 'disabled',
// User settings: Expert configuration
'cache' => true,
'http_connection' => 'curl',
'http_method' => 'post',
'disable_timelimit' => false,
'filter_limit' => '',
'connection_timeout' => 5,
'disable_ssl_verify' => false,
'disable_ssl_verify_host' => false,
'piwik_useragent' => 'php',
'piwik_useragent_string' => 'WP-Piwik',
'dnsprefetch' => false,
'track_datacfasync' => false,
'track_cdnurl' => '',
'track_cdnurlssl' => '',
'force_protocol' => 'disabled',
'remove_type_attribute' => false,
'update_notice' => 'enabled'
), $settings = array (
'name' => '',
'site_id' => NULL,
'noscript_code' => '',
'tracking_code' => '',
'last_tracking_code_update' => 0,
'dashboard_revision' => 0
), $settingsChanged = false;
/**
* Constructor class to prepare settings manager
*
* @param WP_Piwik $wpPiwik
* active WP-Piwik instance
*/
public function __construct($wpPiwik) {
self::$wpPiwik = $wpPiwik;
self::$wpPiwik->log ( 'Store default settings' );
self::$defaultSettings = array (
'globalSettings' => $this->globalSettings,
'settings' => $this->settings
);
self::$wpPiwik->log ( 'Load settings' );
foreach ( $this->globalSettings as $key => $default ) {
$this->globalSettings [$key] = ($this->checkNetworkActivation () ? get_site_option ( 'wp-piwik_global-' . $key, $default ) : get_option ( 'wp-piwik_global-' . $key, $default ));
}
foreach ( $this->settings as $key => $default )
$this->settings [$key] = get_option ( 'wp-piwik-' . $key, $default );
}
/**
* Save all settings as WordPress options
*/
public function save() {
if (! $this->settingsChanged) {
self::$wpPiwik->log ( 'No settings changed yet' );
return;
}
self::$wpPiwik->log ( 'Save settings' );
$this->globalSettings['plugin_display_name'] = htmlspecialchars($this->globalSettings['plugin_display_name'], ENT_QUOTES, 'utf-8');
foreach ( $this->globalSettings as $key => $value ) {
if ( $this->checkNetworkActivation() )
update_site_option ( 'wp-piwik_global-' . $key, $value );
else
update_option ( 'wp-piwik_global-' . $key, $value );
}
foreach ( $this->settings as $key => $value ) {
update_option ( 'wp-piwik-' . $key, $value );
}
global $wp_roles;
if (! is_object ( $wp_roles ))
$wp_roles = new \WP_Roles ();
if (! is_object ( $wp_roles ))
die ( "STILL NO OBJECT" );
foreach ( $wp_roles->role_names as $strKey => $strName ) {
$objRole = get_role ( $strKey );
foreach ( array (
'stealth',
'read_stats'
) as $strCap ) {
$aryCaps = $this->getGlobalOption ( 'capability_' . $strCap );
if (isset ( $aryCaps [$strKey] ) && $aryCaps [$strKey])
$wp_roles->add_cap ( $strKey, 'wp-piwik_' . $strCap );
else $wp_roles->remove_cap ( $strKey, 'wp-piwik_' . $strCap );
}
}
$this->settingsChanged = false;
}
/**
* Get a global option's value which should not be empty
*
* @param string $key
* option key
* @return string option value
*/
public function getNotEmptyGlobalOption($key) {
return isset ( $this->globalSettings [$key] ) && !empty($this->globalSettings [$key]) ? $this->globalSettings [$key] : self::$defaultSettings ['globalSettings'] [$key];
}
/**
* Get a global option's value
*
* @param string $key
* option key
* @return string option value
*/
public function getGlobalOption($key) {
return isset ( $this->globalSettings [$key] ) ? $this->globalSettings [$key] : self::$defaultSettings ['globalSettings'] [$key];
}
/**
* Get an option's value related to a specific blog
*
* @param string $key
* option key
* @param int $blogID
* blog ID (default: current blog)
* @return \WP_Piwik\Register
*/
public function getOption($key, $blogID = null) {
if ($this->checkNetworkActivation () && ! empty ( $blogID )) {
return get_blog_option ( $blogID, 'wp-piwik-'.$key );
}
return isset ( $this->settings [$key] ) ? $this->settings [$key] : self::$defaultSettings ['settings'] [$key];
}
/**
* Set a global option's value
*
* @param string $key
* option key
* @param string $value
* new option value
*/
public function setGlobalOption($key, $value) {
$this->settingsChanged = true;
self::$wpPiwik->log ( 'Changed global option ' . $key . ': ' . (is_array ( $value ) ? serialize ( $value ) : $value) );
$this->globalSettings [$key] = $value;
}
/**
* Set an option's value related to a specific blog
*
* @param string $key
* option key
* @param string $value
* new option value
* @param int $blogID
* blog ID (default: current blog)
*/
public function setOption($key, $value, $blogID = null) {
if (empty( $blogID )) {
$blogID = get_current_blog_id();
}
$this->settingsChanged = true;
self::$wpPiwik->log ( 'Changed option ' . $key . ': ' . $value );
if ($this->checkNetworkActivation ()) {
update_blog_option ( $blogID, 'wp-piwik-'.$key, $value );
}
if ($blogID == get_current_blog_id()) {
$this->settings [$key] = $value;
}
}
/**
* Reset settings to default
*/
public function resetSettings() {
self::$wpPiwik->log ( 'Reset WP-Piwik settings' );
global $wpdb;
if ( $this->checkNetworkActivation() ) {
$aryBlogs = self::getBlogList();
if (is_array($aryBlogs))
foreach ($aryBlogs as $aryBlog) {
switch_to_blog($aryBlog['blog_id']);
$wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE 'wp-piwik-%'");
restore_current_blog();
}
$wpdb->query("DELETE FROM $wpdb->sitemeta WHERE meta_key LIKE 'wp-piwik_global-%'");
}
else $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE 'wp-piwik_global-%'");
}
/**
* Get blog list
*/
public static function getBlogList($limit = null, $page = null, $search = '') {
if ($limit && $page)
$queryLimit = ' LIMIT '.(int) (($page - 1) * $limit).','.(int) $limit;
global $wpdb;
return $wpdb->get_results($wpdb->prepare('SELECT blog_id FROM '.$wpdb->blogs.' WHERE CONCAT(domain, path) LIKE "%%%s%%" AND spam = 0 AND deleted = 0 ORDER BY blog_id'.$queryLimit, $search), ARRAY_A);
}
/**
* Check if plugin is network activated
*
* @return boolean Is network activated?
*/
public function checkNetworkActivation() {
if (! function_exists ( "is_plugin_active_for_network" ))
require_once (ABSPATH . 'wp-admin/includes/plugin.php');
return is_plugin_active_for_network ( 'wp-piwik/wp-piwik.php' );
}
/**
* Apply new configuration
*
* @param array $in
* new configuration set
*/
public function applyChanges($in) {
if (!self::$wpPiwik->isValidOptionsPost())
die("Invalid config changes.");
$in = $this->checkSettings ( $in );
self::$wpPiwik->log ( 'Apply changed settings:' );
foreach ( self::$defaultSettings ['globalSettings'] as $key => $val )
$this->setGlobalOption ( $key, isset ( $in [$key] ) ? $in [$key] : $val );
foreach ( self::$defaultSettings ['settings'] as $key => $val )
$this->setOption ( $key, isset ( $in [$key] ) ? $in [$key] : $val );
$this->setGlobalOption ( 'last_settings_update', time () );
$this->save ();
}
/**
* Apply callback function on new settings
*
* @param array $in
* new configuration set
* @return array configuration set after callback functions were applied
*/
private function checkSettings($in) {
foreach ( $this->checkSettings as $key => $value )
if (isset ( $in [$key] ))
$in [$key] = call_user_func_array ( array (
$this,
$value
), array (
$in [$key],
$in
) );
return $in;
}
/**
* Add slash to Piwik URL if necessary
*
* @param string $value
* Piwik URL
* @param array $in
* configuration set
* @return string Piwik URL
*/
private function checkPiwikUrl($value, $in) {
return substr ( $value, - 1, 1 ) != '/' ? $value . '/' : $value;
}
/**
* Remove &amp;token_auth= from auth token
*
* @param string $value
* Piwik auth token
* @param array $in
* configuration set
* @return string Piwik auth token
*/
private function checkPiwikToken($value, $in) {
return str_replace ( '&token_auth=', '', $value );
}
/**
* Request the site ID (if not set before)
*
* @param string $value
* tracking code
* @param array $in
* configuration set
* @return int Piwik site ID
*/
private function requestPiwikSiteID($value, $in) {
if ($in ['auto_site_config'] && ! $value)
return self::$wpPiwik->getPiwikSiteId();
return $value;
}
/**
* Prepare the tracking code
*
* @param string $value
* tracking code
* @param array $in
* configuration set
* @return string tracking code
*/
private function prepareTrackingCode($value, $in) {
if ($in ['track_mode'] == 'manually' || $in ['track_mode'] == 'disabled') {
$value = stripslashes ( $value );
if ($this->checkNetworkActivation ())
update_site_option ( 'wp-piwik-manually', $value );
return $value;
}
/*$result = self::$wpPiwik->updateTrackingCode ();
echo '<pre>'; print_r($result); echo '</pre>';
$this->setOption ( 'noscript_code', $result ['noscript'] );*/
return; // $result ['script'];
}
/**
* Prepare the nocscript code
*
* @param string $value
* noscript code
* @param array $in
* configuration set
* @return string noscript code
*/
private function prepareNocscriptCode($value, $in) {
if ($in ['track_mode'] == 'manually')
return stripslashes ( $value );
return $this->getOption ( 'noscript_code' );
}
/**
* Get debug data
*
* @return array WP-Piwik settings for debug output
*/
public function getDebugData() {
$debug = array(
'global_settings' => $this->globalSettings,
'settings' => $this->settings
);
$debug['global_settings']['piwik_token'] = !empty($debug['global_settings']['piwik_token'])?'set':'not set';
return $debug;
}
}
<?php
namespace WP_Piwik;
/**
* Manage WP-Piwik settings
*
* @author Andr&eacute; Br&auml;kling
* @package WP_Piwik
*/
class Settings {
/**
*
* @var Environment variables and default settings container
*/
private static $wpPiwik, $defaultSettings;
/**
*
* @var Define callback functions for changed settings
*/
private $checkSettings = array (
'piwik_url' => 'checkPiwikUrl',
'piwik_token' => 'checkPiwikToken',
'site_id' => 'requestPiwikSiteID',
'tracking_code' => 'prepareTrackingCode',
'noscript_code' => 'prepareNocscriptCode'
);
/**
*
* @var Register default configuration set
*/
private $globalSettings = array (
// Plugin settings
'revision' => 0,
'last_settings_update' => 0,
// User settings: Piwik configuration
'piwik_mode' => 'http',
'piwik_url' => '',
'piwik_path' => '',
'piwik_user' => '',
'matomo_user' => '',
'piwik_token' => '',
'auto_site_config' => true,
// User settings: Stats configuration
'default_date' => 'yesterday',
'stats_seo' => false,
'stats_ecommerce' => false,
'dashboard_widget' => false,
'dashboard_ecommerce' => false,
'dashboard_chart' => false,
'dashboard_seo' => false,
'toolbar' => false,
'capability_read_stats' => array (
'administrator' => true
),
'perpost_stats' => "disabled",
'plugin_display_name' => 'Connect Matomo',
'piwik_shortcut' => false,
'shortcodes' => false,
// User settings: Tracking configuration
'track_mode' => 'disabled',
'track_codeposition' => 'footer',
'track_noscript' => false,
'track_nojavascript' => false,
'proxy_url' => '',
'track_content' => 'disabled',
'track_search' => false,
'track_404' => false,
'add_post_annotations' => array(),
'add_customvars_box' => false,
'add_download_extensions' => '',
'set_download_extensions' => '',
'set_link_classes' => '',
'set_download_classes' => '',
'require_consent' => 'disabled',
'disable_cookies' => false,
'limit_cookies' => false,
'limit_cookies_visitor' => 34186669, // Piwik default 13 months
'limit_cookies_session' => 1800, // Piwik default 30 minutes
'limit_cookies_referral' => 15778463, // Piwik default 6 months
'track_admin' => false,
'capability_stealth' => array (),
'track_across' => false,
'track_across_alias' => false,
'track_crossdomain_linking' => false,
'track_feed' => false,
'track_feed_addcampaign' => false,
'track_feed_campaign' => 'feed',
'track_heartbeat' => 0,
'track_user_id' => 'disabled',
// User settings: Expert configuration
'cache' => true,
'http_connection' => 'curl',
'http_method' => 'post',
'disable_timelimit' => false,
'filter_limit' => '',
'connection_timeout' => 5,
'disable_ssl_verify' => false,
'disable_ssl_verify_host' => false,
'piwik_useragent' => 'php',
'piwik_useragent_string' => 'WP-Piwik',
'dnsprefetch' => false,
'track_datacfasync' => false,
'track_cdnurl' => '',
'track_cdnurlssl' => '',
'force_protocol' => 'disabled',
'remove_type_attribute' => false,
'update_notice' => 'enabled'
), $settings = array (
'name' => '',
'site_id' => NULL,
'noscript_code' => '',
'tracking_code' => '',
'last_tracking_code_update' => 0,
'dashboard_revision' => 0
), $settingsChanged = false;
/**
* Constructor class to prepare settings manager
*
* @param WP_Piwik $wpPiwik
* active WP-Piwik instance
*/
public function __construct($wpPiwik) {
self::$wpPiwik = $wpPiwik;
self::$wpPiwik->log ( 'Store default settings' );
self::$defaultSettings = array (
'globalSettings' => $this->globalSettings,
'settings' => $this->settings
);
self::$wpPiwik->log ( 'Load settings' );
foreach ( $this->globalSettings as $key => $default ) {
$this->globalSettings [$key] = ($this->checkNetworkActivation () ? get_site_option ( 'wp-piwik_global-' . $key, $default ) : get_option ( 'wp-piwik_global-' . $key, $default ));
}
foreach ( $this->settings as $key => $default )
$this->settings [$key] = get_option ( 'wp-piwik-' . $key, $default );
}
/**
* Save all settings as WordPress options
*/
public function save() {
if (! $this->settingsChanged) {
self::$wpPiwik->log ( 'No settings changed yet' );
return;
}
self::$wpPiwik->log ( 'Save settings' );
$this->globalSettings['plugin_display_name'] = htmlspecialchars($this->globalSettings['plugin_display_name'], ENT_QUOTES, 'utf-8');
foreach ( $this->globalSettings as $key => $value ) {
if ( $this->checkNetworkActivation() )
update_site_option ( 'wp-piwik_global-' . $key, $value );
else
update_option ( 'wp-piwik_global-' . $key, $value );
}
foreach ( $this->settings as $key => $value ) {
update_option ( 'wp-piwik-' . $key, $value );
}
global $wp_roles;
if (! is_object ( $wp_roles ))
$wp_roles = new \WP_Roles ();
if (! is_object ( $wp_roles ))
die ( "STILL NO OBJECT" );
foreach ( $wp_roles->role_names as $strKey => $strName ) {
$objRole = get_role ( $strKey );
foreach ( array (
'stealth',
'read_stats'
) as $strCap ) {
$aryCaps = $this->getGlobalOption ( 'capability_' . $strCap );
if (isset ( $aryCaps [$strKey] ) && $aryCaps [$strKey])
$wp_roles->add_cap ( $strKey, 'wp-piwik_' . $strCap );
else $wp_roles->remove_cap ( $strKey, 'wp-piwik_' . $strCap );
}
}
$this->settingsChanged = false;
}
/**
* Get a global option's value which should not be empty
*
* @param string $key
* option key
* @return string option value
*/
public function getNotEmptyGlobalOption($key) {
return isset ( $this->globalSettings [$key] ) && !empty($this->globalSettings [$key]) ? $this->globalSettings [$key] : self::$defaultSettings ['globalSettings'] [$key];
}
/**
* Get a global option's value
*
* @param string $key
* option key
* @return string option value
*/
public function getGlobalOption($key) {
return isset ( $this->globalSettings [$key] ) ? $this->globalSettings [$key] : self::$defaultSettings ['globalSettings'] [$key];
}
/**
* Get an option's value related to a specific blog
*
* @param string $key
* option key
* @param int $blogID
* blog ID (default: current blog)
* @return \WP_Piwik\Register
*/
public function getOption($key, $blogID = null) {
if ($this->checkNetworkActivation () && ! empty ( $blogID )) {
return get_blog_option ( $blogID, 'wp-piwik-'.$key );
}
return isset ( $this->settings [$key] ) ? $this->settings [$key] : self::$defaultSettings ['settings'] [$key];
}
/**
* Set a global option's value
*
* @param string $key
* option key
* @param string $value
* new option value
*/
public function setGlobalOption($key, $value) {
$this->settingsChanged = true;
self::$wpPiwik->log ( 'Changed global option ' . $key . ': ' . (is_array ( $value ) ? serialize ( $value ) : $value) );
$this->globalSettings [$key] = $value;
}
/**
* Set an option's value related to a specific blog
*
* @param string $key
* option key
* @param string $value
* new option value
* @param int $blogID
* blog ID (default: current blog)
*/
public function setOption($key, $value, $blogID = null) {
if (empty( $blogID )) {
$blogID = get_current_blog_id();
}
$this->settingsChanged = true;
self::$wpPiwik->log ( 'Changed option ' . $key . ': ' . $value );
if ($this->checkNetworkActivation ()) {
update_blog_option ( $blogID, 'wp-piwik-'.$key, $value );
}
if ($blogID == get_current_blog_id()) {
$this->settings [$key] = $value;
}
}
/**
* Reset settings to default
*/
public function resetSettings() {
self::$wpPiwik->log ( 'Reset WP-Piwik settings' );
global $wpdb;
if ( $this->checkNetworkActivation() ) {
$aryBlogs = self::getBlogList();
if (is_array($aryBlogs))
foreach ($aryBlogs as $aryBlog) {
switch_to_blog($aryBlog['blog_id']);
$wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE 'wp-piwik-%'");
restore_current_blog();
}
$wpdb->query("DELETE FROM $wpdb->sitemeta WHERE meta_key LIKE 'wp-piwik_global-%'");
}
else $wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE 'wp-piwik_global-%'");
}
/**
* Get blog list
*/
public static function getBlogList($limit = null, $page = null, $search = '') {
if ($limit && $page)
$queryLimit = ' LIMIT '.(int) (($page - 1) * $limit).','.(int) $limit;
global $wpdb;
return $wpdb->get_results($wpdb->prepare('SELECT blog_id FROM '.$wpdb->blogs.' WHERE CONCAT(domain, path) LIKE "%%%s%%" AND spam = 0 AND deleted = 0 ORDER BY blog_id'.$queryLimit, $search), ARRAY_A);
}
/**
* Check if plugin is network activated
*
* @return boolean Is network activated?
*/
public function checkNetworkActivation() {
if (! function_exists ( "is_plugin_active_for_network" ))
require_once (ABSPATH . 'wp-admin/includes/plugin.php');
return is_plugin_active_for_network ( 'wp-piwik/wp-piwik.php' );
}
/**
* Apply new configuration
*
* @param array $in
* new configuration set
*/
public function applyChanges($in) {
if (!self::$wpPiwik->isValidOptionsPost())
die("Invalid config changes.");
$in = $this->checkSettings ( $in );
self::$wpPiwik->log ( 'Apply changed settings:' );
foreach ( self::$defaultSettings ['globalSettings'] as $key => $val )
$this->setGlobalOption ( $key, isset ( $in [$key] ) ? $in [$key] : $val );
foreach ( self::$defaultSettings ['settings'] as $key => $val )
$this->setOption ( $key, isset ( $in [$key] ) ? $in [$key] : $val );
$this->setGlobalOption ( 'last_settings_update', time () );
$this->save ();
}
/**
* Apply callback function on new settings
*
* @param array $in
* new configuration set
* @return array configuration set after callback functions were applied
*/
private function checkSettings($in) {
foreach ( $this->checkSettings as $key => $value )
if (isset ( $in [$key] ))
$in [$key] = call_user_func_array ( array (
$this,
$value
), array (
$in [$key],
$in
) );
return $in;
}
/**
* Add slash to Piwik URL if necessary
*
* @param string $value
* Piwik URL
* @param array $in
* configuration set
* @return string Piwik URL
*/
private function checkPiwikUrl($value, $in) {
return substr ( $value, - 1, 1 ) != '/' ? $value . '/' : $value;
}
/**
* Remove &amp;token_auth= from auth token
*
* @param string $value
* Piwik auth token
* @param array $in
* configuration set
* @return string Piwik auth token
*/
private function checkPiwikToken($value, $in) {
return str_replace ( '&token_auth=', '', $value );
}
/**
* Request the site ID (if not set before)
*
* @param string $value
* tracking code
* @param array $in
* configuration set
* @return int Piwik site ID
*/
private function requestPiwikSiteID($value, $in) {
if ($in ['auto_site_config'] && ! $value)
return self::$wpPiwik->getPiwikSiteId();
return $value;
}
/**
* Prepare the tracking code
*
* @param string $value
* tracking code
* @param array $in
* configuration set
* @return string tracking code
*/
private function prepareTrackingCode($value, $in) {
if ($in ['track_mode'] == 'manually' || $in ['track_mode'] == 'disabled') {
$value = stripslashes ( $value );
if ($this->checkNetworkActivation ())
update_site_option ( 'wp-piwik-manually', $value );
return $value;
}
/*$result = self::$wpPiwik->updateTrackingCode ();
echo '<pre>'; print_r($result); echo '</pre>';
$this->setOption ( 'noscript_code', $result ['noscript'] );*/
return; // $result ['script'];
}
/**
* Prepare the nocscript code
*
* @param string $value
* noscript code
* @param array $in
* configuration set
* @return string noscript code
*/
private function prepareNocscriptCode($value, $in) {
if ($in ['track_mode'] == 'manually')
return stripslashes ( $value );
return $this->getOption ( 'noscript_code' );
}
/**
* Get debug data
*
* @return array WP-Piwik settings for debug output
*/
public function getDebugData() {
$debug = array(
'global_settings' => $this->globalSettings,
'settings' => $this->settings
);
$debug['global_settings']['piwik_token'] = !empty($debug['global_settings']['piwik_token'])?'set':'not set';
return $debug;
}
}

View File

@ -1,167 +1,167 @@
<?php
namespace WP_Piwik;
class TrackingCode {
private static $wpPiwik, $piwikUrl = false;
private $trackingCode;
public $is404 = false, $isSearch = false, $isUsertracking = false;
public function __construct($wpPiwik) {
self::$wpPiwik = $wpPiwik;
if (! self::$wpPiwik->isCurrentTrackingCode () || ! self::$wpPiwik->getOption ( 'tracking_code' ) || strpos( self::$wpPiwik->getOption ( 'tracking_code' ), '{"result":"error",' ) !== false )
self::$wpPiwik->updateTrackingCode ();
$this->trackingCode = (self::$wpPiwik->isNetworkMode () && self::$wpPiwik->getGlobalOption ( 'track_mode' ) == 'manually') ? get_site_option ( 'wp-piwik-manually' ) : self::$wpPiwik->getOption ( 'tracking_code' );
}
public function getTrackingCode() {
if ($this->isUsertracking)
$this->applyUserTracking ();
if ($this->is404)
$this->apply404Changes ();
if ($this->isSearch)
$this->applySearchChanges ();
if (is_single () || is_page())
$this->addCustomValues ();
$this->trackingCode = apply_filters('wp-piwik_tracking_code', $this->trackingCode);
return $this->trackingCode;
}
public static function prepareTrackingCode($code, $settings, $logger) {
global $current_user;
$logger->log ( 'Apply tracking code changes:' );
$settings->setOption ( 'last_tracking_code_update', time () );
if (preg_match ( '/var u="([^"]*)";/', $code, $hits )) {
$fetchedProxyUrl = $hits [1];
} else $fetchedProxyUrl = '';
if ($settings->getGlobalOption ( 'remove_type_attribute')) {
$code = str_replace (
array( ' type="text/javascript"', " type='text/javascript'" ),
'',
$code
);
}
if ($settings->getGlobalOption ( 'track_mode' ) == 'js')
$code = str_replace ( array (
'piwik.js',
'piwik.php',
'matomo.js',
'matomo.php'
), 'js/index.php', $code );
elseif ($settings->getGlobalOption ( 'track_mode' ) == 'proxy') {
$code = str_replace ( 'piwik.js', 'matomo.php', $code );
$code = str_replace ( 'matomo.js', 'matomo.php', $code );
$code = str_replace ( 'piwik.php', 'matomo.php', $code );
$proxy = str_replace ( array (
'https://',
'http://'
), '//', plugins_url ( 'wp-piwik' ) . '/proxy' ) . '/';
$code = preg_replace ( '/var u="([^"]*)";/', 'var u="' . $proxy . '"', $code );
$code = preg_replace ( '/img src="([^"]*)piwik.php/', 'img src="' . $proxy . 'matomo.php', $code );
$code = preg_replace ( '/img src="([^"]*)matomo.php/', 'img src="' . $proxy . 'matomo.php', $code );
}
if ($settings->getGlobalOption ( 'track_cdnurl' ) || $settings->getGlobalOption ( 'track_cdnurlssl' ))
$code = str_replace ( array (
"var d=doc",
"g.src=u+"
), array (
"var ucdn=(('https:' == document.location.protocol) ? 'https://" . ($settings->getGlobalOption ( 'track_cdnurlssl' ) ? $settings->getGlobalOption ( 'track_cdnurlssl' ) : $settings->getGlobalOption ( 'track_cdnurl' )) . "/' : 'http://" . ($settings->getGlobalOption ( 'track_cdnurl' ) ? $settings->getGlobalOption ( 'track_cdnurl' ) : $settings->getGlobalOption ( 'track_cdnurlssl' )) . "/');\nvar d=doc",
"g.src=ucdn+"
), $code );
if ($settings->getGlobalOption ( 'track_datacfasync' ))
$code = str_replace ( '<script type', '<script data-cfasync="false" type', $code );
if ($settings->getGlobalOption ( 'set_download_extensions' ))
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['setDownloadExtensions', '" . ($settings->getGlobalOption ( 'set_download_extensions' )) . "']);\n_paq.push(['trackPageView']);", $code );
if ($settings->getGlobalOption ( 'add_download_extensions' ))
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['addDownloadExtensions', '" . ($settings->getGlobalOption ( 'add_download_extensions' )) . "']);\n_paq.push(['trackPageView']);", $code );
if ($settings->getGlobalOption ( 'set_download_classes' ))
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['setDownloadClasses', '" . ($settings->getGlobalOption ( 'set_download_classes' )) . "']);\n_paq.push(['trackPageView']);", $code );
if ($settings->getGlobalOption ( 'set_link_classes' ))
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['setLinkClasses', '" . ($settings->getGlobalOption ( 'set_link_classes' )) . "']);\n_paq.push(['trackPageView']);", $code );
if ($settings->getGlobalOption ( 'limit_cookies' ))
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['setVisitorCookieTimeout', '" . $settings->getGlobalOption ( 'limit_cookies_visitor' ) . "']);\n_paq.push(['setSessionCookieTimeout', '" . $settings->getGlobalOption ( 'limit_cookies_session' ) . "']);\n_paq.push(['setReferralCookieTimeout', '" . $settings->getGlobalOption ( 'limit_cookies_referral' ) . "']);\n_paq.push(['trackPageView']);", $code );
if ($settings->getGlobalOption ( 'force_protocol' ) != 'disabled')
$code = str_replace ( '"//', '"' . $settings->getGlobalOption ( 'force_protocol' ) . '://', $code );
if ($settings->getGlobalOption ( 'track_content' ) == 'all')
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['trackPageView']);\n_paq.push(['trackAllContentImpressions']);", $code );
elseif ($settings->getGlobalOption ( 'track_content' ) == 'visible')
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['trackPageView']);\n_paq.push(['trackVisibleContentImpressions']);", $code );
if ((int) $settings->getGlobalOption ( 'track_heartbeat' ) > 0)
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['trackPageView']);\n_paq.push(['enableHeartBeatTimer', ".(int) $settings->getGlobalOption ( 'track_heartbeat' )."]);", $code );
if ($settings->getGlobalOption ( 'require_consent' ) == 'consent') {
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['requireConsent']);\n_paq.push(['trackPageView']);", $code );
} elseif ($settings->getGlobalOption ( 'require_consent' ) == 'cookieconsent') {
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['requireCookieConsent']);\n_paq.push(['trackPageView']);", $code );
}
$noScript = array ();
preg_match ( '/<noscript>(.*)<\/noscript>/', $code, $noScript );
if (isset ( $noScript [0] )) {
if ($settings->getGlobalOption ( 'track_nojavascript' ))
$noScript [0] = str_replace ( '?idsite', '?rec=1&idsite', $noScript [0] );
$noScript = $noScript [0];
} else
$noScript = '';
$script = preg_replace ( '/<noscript>(.*)<\/noscript>/', '', $code );
$script = preg_replace ( '/\s+(\r\n|\r|\n)/', '$1', $script );
$logger->log ( 'Finished tracking code: ' . $script );
$logger->log ( 'Finished noscript code: ' . $noScript );
return array (
'script' => $script,
'noscript' => $noScript,
'proxy' => $fetchedProxyUrl
);
}
private function apply404Changes() {
self::$wpPiwik->log ( 'Apply 404 changes. Blog ID: ' . get_current_blog_id () . ' Site ID: ' . self::$wpPiwik->getOption ( 'site_id' ) );
$this->trackingCode = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['setDocumentTitle', '404/URL = '+String(document.location.pathname+document.location.search).replace(/\//g,'%2f') + '/From = ' + String(document.referrer).replace(/\//g,'%2f')]);\n_paq.push(['trackPageView']);", $this->trackingCode );
}
private function applySearchChanges() {
global $wp_query;
self::$wpPiwik->log ( 'Apply search tracking changes. Blog ID: ' . get_current_blog_id () . ' Site ID: ' . self::$wpPiwik->getOption ( 'site_id' ) );
$intResultCount = $wp_query->found_posts;
$this->trackingCode = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['trackSiteSearch','" . get_search_query () . "', false, " . $intResultCount . "]);\n_paq.push(['trackPageView']);", $this->trackingCode );
}
private function applyUserTracking() {
$pkUserId = null;
if (\is_user_logged_in()) {
// Get the User ID Admin option, and the current user's data
$uidFrom = self::$wpPiwik->getGlobalOption ( 'track_user_id' );
$current_user = wp_get_current_user(); // current user
// Get the user ID based on the admin setting
if ( $uidFrom == 'uid' ) {
$pkUserId = $current_user->ID;
} elseif ( $uidFrom == 'email' ) {
$pkUserId = $current_user->user_email;
} elseif ( $uidFrom == 'username' ) {
$pkUserId = $current_user->user_login;
} elseif ( $uidFrom == 'displayname' ) {
$pkUserId = $current_user->display_name;
}
}
$pkUserId = apply_filters('wp-piwik_tracking_user_id', $pkUserId);
// Check we got a User ID to track, and track it
if ( isset( $pkUserId ) && ! empty( $pkUserId ))
$this->trackingCode = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['setUserId', '" . esc_js( $pkUserId ) . "']);\n_paq.push(['trackPageView']);", $this->trackingCode );
}
private function addCustomValues() {
$customVars = '';
for($i = 1; $i <= 5; $i ++) {
$postId = get_the_ID ();
$metaKey = get_post_meta ( $postId, 'wp-piwik_custom_cat' . $i, true );
$metaVal = get_post_meta ( $postId, 'wp-piwik_custom_val' . $i, true );
if (! empty ( $metaKey ) && ! empty ( $metaVal ))
$customVars .= "_paq.push(['setCustomVariable'," . $i . ", '" . $metaKey . "', '" . $metaVal . "', 'page']);\n";
}
if (! empty ( $customVars ))
$this->trackingCode = str_replace ( "_paq.push(['trackPageView']);", $customVars . "_paq.push(['trackPageView']);", $this->trackingCode );
}
}
<?php
namespace WP_Piwik;
class TrackingCode {
private static $wpPiwik, $piwikUrl = false;
private $trackingCode;
public $is404 = false, $isSearch = false, $isUsertracking = false;
public function __construct($wpPiwik) {
self::$wpPiwik = $wpPiwik;
if (! self::$wpPiwik->isCurrentTrackingCode () || ! self::$wpPiwik->getOption ( 'tracking_code' ) || strpos( self::$wpPiwik->getOption ( 'tracking_code' ), '{"result":"error",' ) !== false )
self::$wpPiwik->updateTrackingCode ();
$this->trackingCode = (self::$wpPiwik->isNetworkMode () && self::$wpPiwik->getGlobalOption ( 'track_mode' ) == 'manually') ? get_site_option ( 'wp-piwik-manually' ) : self::$wpPiwik->getOption ( 'tracking_code' );
}
public function getTrackingCode() {
if ($this->isUsertracking)
$this->applyUserTracking ();
if ($this->is404)
$this->apply404Changes ();
if ($this->isSearch)
$this->applySearchChanges ();
if (is_single () || is_page())
$this->addCustomValues ();
$this->trackingCode = apply_filters('wp-piwik_tracking_code', $this->trackingCode);
return $this->trackingCode;
}
public static function prepareTrackingCode($code, $settings, $logger) {
global $current_user;
$logger->log ( 'Apply tracking code changes:' );
$settings->setOption ( 'last_tracking_code_update', time () );
if (preg_match ( '/var u="([^"]*)";/', $code, $hits )) {
$fetchedProxyUrl = $hits [1];
} else $fetchedProxyUrl = '';
if ($settings->getGlobalOption ( 'remove_type_attribute')) {
$code = str_replace (
array( ' type="text/javascript"', " type='text/javascript'" ),
'',
$code
);
}
if ($settings->getGlobalOption ( 'track_mode' ) == 'js')
$code = str_replace ( array (
'piwik.js',
'piwik.php',
'matomo.js',
'matomo.php'
), 'js/index.php', $code );
elseif ($settings->getGlobalOption ( 'track_mode' ) == 'proxy') {
$code = str_replace ( 'piwik.js', 'matomo.php', $code );
$code = str_replace ( 'matomo.js', 'matomo.php', $code );
$code = str_replace ( 'piwik.php', 'matomo.php', $code );
$proxy = str_replace ( array (
'https://',
'http://'
), '//', plugins_url ( 'wp-piwik' ) . '/proxy' ) . '/';
$code = preg_replace ( '/var u="([^"]*)";/', 'var u="' . $proxy . '"', $code );
$code = preg_replace ( '/img src="([^"]*)piwik.php/', 'img src="' . $proxy . 'matomo.php', $code );
$code = preg_replace ( '/img src="([^"]*)matomo.php/', 'img src="' . $proxy . 'matomo.php', $code );
}
if ($settings->getGlobalOption ( 'track_cdnurl' ) || $settings->getGlobalOption ( 'track_cdnurlssl' ))
$code = str_replace ( array (
"var d=doc",
"g.src=u+"
), array (
"var ucdn=(('https:' == document.location.protocol) ? 'https://" . ($settings->getGlobalOption ( 'track_cdnurlssl' ) ? $settings->getGlobalOption ( 'track_cdnurlssl' ) : $settings->getGlobalOption ( 'track_cdnurl' )) . "/' : 'http://" . ($settings->getGlobalOption ( 'track_cdnurl' ) ? $settings->getGlobalOption ( 'track_cdnurl' ) : $settings->getGlobalOption ( 'track_cdnurlssl' )) . "/');\nvar d=doc",
"g.src=ucdn+"
), $code );
if ($settings->getGlobalOption ( 'track_datacfasync' ))
$code = str_replace ( '<script type', '<script data-cfasync="false" type', $code );
if ($settings->getGlobalOption ( 'set_download_extensions' ))
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['setDownloadExtensions', '" . ($settings->getGlobalOption ( 'set_download_extensions' )) . "']);\n_paq.push(['trackPageView']);", $code );
if ($settings->getGlobalOption ( 'add_download_extensions' ))
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['addDownloadExtensions', '" . ($settings->getGlobalOption ( 'add_download_extensions' )) . "']);\n_paq.push(['trackPageView']);", $code );
if ($settings->getGlobalOption ( 'set_download_classes' ))
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['setDownloadClasses', '" . ($settings->getGlobalOption ( 'set_download_classes' )) . "']);\n_paq.push(['trackPageView']);", $code );
if ($settings->getGlobalOption ( 'set_link_classes' ))
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['setLinkClasses', '" . ($settings->getGlobalOption ( 'set_link_classes' )) . "']);\n_paq.push(['trackPageView']);", $code );
if ($settings->getGlobalOption ( 'limit_cookies' ))
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['setVisitorCookieTimeout', '" . $settings->getGlobalOption ( 'limit_cookies_visitor' ) . "']);\n_paq.push(['setSessionCookieTimeout', '" . $settings->getGlobalOption ( 'limit_cookies_session' ) . "']);\n_paq.push(['setReferralCookieTimeout', '" . $settings->getGlobalOption ( 'limit_cookies_referral' ) . "']);\n_paq.push(['trackPageView']);", $code );
if ($settings->getGlobalOption ( 'force_protocol' ) != 'disabled')
$code = str_replace ( '"//', '"' . $settings->getGlobalOption ( 'force_protocol' ) . '://', $code );
if ($settings->getGlobalOption ( 'track_content' ) == 'all')
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['trackPageView']);\n_paq.push(['trackAllContentImpressions']);", $code );
elseif ($settings->getGlobalOption ( 'track_content' ) == 'visible')
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['trackPageView']);\n_paq.push(['trackVisibleContentImpressions']);", $code );
if ((int) $settings->getGlobalOption ( 'track_heartbeat' ) > 0)
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['trackPageView']);\n_paq.push(['enableHeartBeatTimer', ".(int) $settings->getGlobalOption ( 'track_heartbeat' )."]);", $code );
if ($settings->getGlobalOption ( 'require_consent' ) == 'consent') {
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['requireConsent']);\n_paq.push(['trackPageView']);", $code );
} elseif ($settings->getGlobalOption ( 'require_consent' ) == 'cookieconsent') {
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['requireCookieConsent']);\n_paq.push(['trackPageView']);", $code );
}
$noScript = array ();
preg_match ( '/<noscript>(.*)<\/noscript>/', $code, $noScript );
if (isset ( $noScript [0] )) {
if ($settings->getGlobalOption ( 'track_nojavascript' ))
$noScript [0] = str_replace ( '?idsite', '?rec=1&idsite', $noScript [0] );
$noScript = $noScript [0];
} else
$noScript = '';
$script = preg_replace ( '/<noscript>(.*)<\/noscript>/', '', $code );
$script = preg_replace ( '/\s+(\r\n|\r|\n)/', '$1', $script );
$logger->log ( 'Finished tracking code: ' . $script );
$logger->log ( 'Finished noscript code: ' . $noScript );
return array (
'script' => $script,
'noscript' => $noScript,
'proxy' => $fetchedProxyUrl
);
}
private function apply404Changes() {
self::$wpPiwik->log ( 'Apply 404 changes. Blog ID: ' . get_current_blog_id () . ' Site ID: ' . self::$wpPiwik->getOption ( 'site_id' ) );
$this->trackingCode = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['setDocumentTitle', '404/URL = '+String(document.location.pathname+document.location.search).replace(/\//g,'%2f') + '/From = ' + String(document.referrer).replace(/\//g,'%2f')]);\n_paq.push(['trackPageView']);", $this->trackingCode );
}
private function applySearchChanges() {
global $wp_query;
self::$wpPiwik->log ( 'Apply search tracking changes. Blog ID: ' . get_current_blog_id () . ' Site ID: ' . self::$wpPiwik->getOption ( 'site_id' ) );
$intResultCount = $wp_query->found_posts;
$this->trackingCode = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['trackSiteSearch','" . get_search_query () . "', false, " . $intResultCount . "]);\n_paq.push(['trackPageView']);", $this->trackingCode );
}
private function applyUserTracking() {
$pkUserId = null;
if (\is_user_logged_in()) {
// Get the User ID Admin option, and the current user's data
$uidFrom = self::$wpPiwik->getGlobalOption ( 'track_user_id' );
$current_user = wp_get_current_user(); // current user
// Get the user ID based on the admin setting
if ( $uidFrom == 'uid' ) {
$pkUserId = $current_user->ID;
} elseif ( $uidFrom == 'email' ) {
$pkUserId = $current_user->user_email;
} elseif ( $uidFrom == 'username' ) {
$pkUserId = $current_user->user_login;
} elseif ( $uidFrom == 'displayname' ) {
$pkUserId = $current_user->display_name;
}
}
$pkUserId = apply_filters('wp-piwik_tracking_user_id', $pkUserId);
// Check we got a User ID to track, and track it
if ( isset( $pkUserId ) && ! empty( $pkUserId ))
$this->trackingCode = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['setUserId', '" . esc_js( $pkUserId ) . "']);\n_paq.push(['trackPageView']);", $this->trackingCode );
}
private function addCustomValues() {
$customVars = '';
for($i = 1; $i <= 5; $i ++) {
$postId = get_the_ID ();
$metaKey = get_post_meta ( $postId, 'wp-piwik_custom_cat' . $i, true );
$metaVal = get_post_meta ( $postId, 'wp-piwik_custom_val' . $i, true );
if (! empty ( $metaKey ) && ! empty ( $metaVal ))
$customVars .= "_paq.push(['setCustomVariable'," . $i . ", '" . $metaKey . "', '" . $metaVal . "', 'page']);\n";
}
if (! empty ( $customVars ))
$this->trackingCode = str_replace ( "_paq.push(['trackPageView']);", $customVars . "_paq.push(['trackPageView']);", $this->trackingCode );
}
}

View File

@ -1,435 +1,435 @@
<?php
namespace WP_Piwik;
use WP_Piwik;
/**
* Abstract widget class
*
* @author Andr&eacute; Br&auml;kling
* @package WP_Piwik
*/
abstract class Widget
{
/**
*
* @var WP_Piwik
*/
protected static $wpPiwik;
/**
* @var Settings
*/
protected static $settings;
protected $isShortcode = false, $method = '', $title = '', $context = 'side', $priority = 'core', $parameter = array(), $apiID = array(), $pageId = 'dashboard', $blogId = null, $name = 'Value', $limit = 10, $content = '', $output = '';
/**
* Widget constructor
*
* @param WP_Piwik $wpPiwik
* current WP-Piwik object
* @param Settings $settings
* current WP-Piwik settings
* @param string $pageId
* WordPress page ID (default: dashboard)
* @param string $context
* WordPress meta box context (defualt: side)
* @param string $priority
* WordPress meta box priority (default: default)
* @param array $params
* widget parameters (default: empty array)
* @param boolean $isShortcode
* is the widget shown inline? (default: false)
*/
public function __construct($wpPiwik, $settings, $pageId = 'dashboard', $context = 'side', $priority = 'default', $params = array(), $isShortcode = false)
{
self::$wpPiwik = $wpPiwik;
self::$settings = $settings;
$this->pageId = $pageId;
$this->context = $context;
$this->priority = $priority;
if (self::$settings->checkNetworkActivation() && function_exists('is_super_admin') && is_super_admin() && isset ($_GET ['wpmu_show_stats'])) {
switch_to_blog(( int )$_GET ['wpmu_show_stats']);
$this->blogId = get_current_blog_id();
restore_current_blog();
}
$this->isShortcode = $isShortcode;
$prefix = ($this->pageId == 'dashboard' ? self::$settings->getGlobalOption('plugin_display_name') . ' - ' : '');
$this->configure($prefix, $params);
if (is_array($this->method))
foreach ($this->method as $method) {
$this->apiID [$method] = Request::register($method, $this->parameter);
self::$wpPiwik->log("Register request: " . $this->apiID [$method]);
}
else {
$this->apiID [$this->method] = Request::register($this->method, $this->parameter);
self::$wpPiwik->log("Register request: " . $this->apiID [$this->method]);
}
if ($this->isShortcode)
return;
add_meta_box($this->getName(), $this->title, array(
$this,
'show'
), $pageId, $this->context, $this->priority);
}
/**
* Conifguration dummy method
*
* @param string $prefix
* metabox title prefix (default: empty)
* @param array $params
* widget parameters (default: empty array)
*/
protected function configure($prefix = '', $params = array())
{
}
/**
* Default show widget method, handles default Piwik output
*/
public function show()
{
$response = self::$wpPiwik->request($this->apiID [$this->method]);
if (!empty ($response ['result']) && $response ['result'] == 'error')
$this->out('<strong>' . __('Piwik error', 'wp-piwik') . ':</strong> ' . htmlentities($response ['message'], ENT_QUOTES, 'utf-8'));
else {
if (isset ($response [0] ['nb_uniq_visitors']))
$unique = 'nb_uniq_visitors';
else
$unique = 'sum_daily_nb_uniq_visitors';
$tableHead = array(
'label' => __($this->name, 'wp-piwik')
);
$tableHead [$unique] = __('Unique', 'wp-piwik');
if (isset ($response [0] ['nb_visits']))
$tableHead ['nb_visits'] = __('Visits', 'wp-piwik');
if (isset ($response [0] ['nb_hits']))
$tableHead ['nb_hits'] = __('Hits', 'wp-piwik');
if (isset ($response [0] ['nb_actions']))
$tableHead ['nb_actions'] = __('Actions', 'wp-piwik');
$tableBody = array();
$count = 0;
if (is_array($response))
foreach ($response as $rowKey => $row) {
$count++;
$tableBody [$rowKey] = array();
foreach ($tableHead as $key => $value)
$tableBody [$rowKey] [] = isset ($row [$key]) ? $row [$key] : '-';
if ($count == 10)
break;
}
$this->table($tableHead, $tableBody, null);
}
}
/**
* Display or store shortcode output
*/
protected function out($output)
{
if ($this->isShortcode)
$this->output .= $output;
else echo $output;
}
/**
* Return shortcode output
*/
public function get()
{
return $this->output;
}
/**
* Display a HTML table
*
* @param array $thead
* table header content (array of cells)
* @param array $tbody
* table body content (array of rows)
* @param array $tfoot
* table footer content (array of cells)
* @param string $class
* CSSclass name to apply on table sections
* @param string $javaScript
* array of javascript code to apply on body rows
*/
protected function table($thead, $tbody = array(), $tfoot = array(), $class = false, $javaScript = array(), $classes = array())
{
$this->out('<div class="table"><table class="widefat wp-piwik-table">');
if ($this->isShortcode && $this->title) {
$colspan = !empty ($tbody) ? count($tbody[0]) : 2;
$this->out('<tr><th colspan="' . $colspan . '">' . $this->title . '</th></tr>');
}
if (!empty ($thead))
$this->tabHead($thead, $class);
if (!empty ($tbody))
$this->tabBody($tbody, $class, $javaScript, $classes);
else
$this->out('<tr><td colspan="10">' . __('No data available.', 'wp-piwik') . '</td></tr>');
if (!empty ($tfoot))
$this->tabFoot($tfoot, $class);
$this->out('</table></div>');
}
/**
* Display a HTML table header
*
* @param array $thead
* array of cells
* @param string $class
* CSS class to apply
*/
private function tabHead($thead, $class = false)
{
$this->out('<thead' . ($class ? ' class="' . $class . '"' : '') . '><tr>');
$count = 0;
foreach ($thead as $value)
$this->out('<th' . ($count++ ? ' class="right"' : '') . '>' . $value . '</th>');
$this->out('</tr></thead>');
}
/**
* Display a HTML table body
*
* @param array $tbody
* array of rows, each row containing an array of cells
* @param string $class
* CSS class to apply
* @param array $javaScript
* array of javascript code to apply (one item per row)
*/
private function tabBody($tbody, $class = "", $javaScript = array(), $classes = array())
{
$this->out('<tbody' . ($class ? ' class="' . $class . '"' : '') . '>');
foreach ($tbody as $key => $trow)
$this->tabRow($trow, isset($javaScript [$key]) ? $javaScript [$key] : '', isset ($classes [$key]) ? $classes [$key] : '');
$this->out('</tbody>');
}
/**
* Display a HTML table footer
*
* @param array $tfoor
* array of cells
* @param string $class
* CSS class to apply
*/
private function tabFoot($tfoot, $class = false)
{
$this->out('<tfoot' . ($class ? ' class="' . $class . '"' : '') . '><tr>');
$count = 0;
foreach ($tfoot as $value)
$this->out('<td' . ($count++ ? ' class="right"' : '') . '>' . $value . '</td>');
$this->out('</tr></tfoot>');
}
/**
* Display a HTML table row
*
* @param array $trow
* array of cells
* @param string $javaScript
* javascript code to apply
*/
private function tabRow($trow, $javaScript = '', $class = '')
{
$this->out('<tr' . (!empty ($javaScript) ? ' onclick="' . $javaScript . '"' : '') . (!empty ($class) ? ' class="' . $class . '"' : '') . '>');
$count = 0;
foreach ($trow as $tcell)
$this->out('<td' . ($count++ ? ' class="right"' : '') . '>' . $tcell . '</td>');
$this->out('</tr>');
}
/**
* Get the current request's Piwik time settings
*
* @return array time settings: period => Piwik period, date => requested date, description => time description to show in widget title
*/
protected function getTimeSettings()
{
switch (self::$settings->getGlobalOption('default_date')) {
case 'today' :
$period = 'day';
$date = 'today';
$description = __('today', 'wp-piwik');
break;
case 'current_month' :
$period = 'month';
$date = 'today';
$description = __('current month', 'wp-piwik');
break;
case 'last_month' :
$period = 'month';
$date = date("Y-m-d", strtotime("last day of previous month"));
$description = __('last month', 'wp-piwik');
break;
case 'current_week' :
$period = 'week';
$date = 'today';
$description = __('current week', 'wp-piwik');
break;
case 'last_week' :
$period = 'week';
$date = date("Y-m-d", strtotime("-1 week"));
$description = __('last week', 'wp-piwik');
break;
case 'yesterday' :
$period = 'day';
$date = 'yesterday';
$description = __('yesterday', 'wp-piwik');
break;
default :
break;
}
return array(
'period' => $period,
'date' => isset ($_GET ['date']) ? ( int )$_GET ['date'] : $date,
'description' => isset ($_GET ['date']) ? $this->dateFormat($_GET ['date'], $period) : $description
);
}
/**
* Format a date to show in widget
*
* @param string $date
* date string
* @param string $period
* Piwik period
* @return string formatted date
*/
protected function dateFormat($date, $period = 'day')
{
$prefix = '';
switch ($period) {
case 'week' :
$prefix = __('week', 'wp-piwik') . ' ';
$format = 'W/Y';
break;
case 'short_week' :
$format = 'W';
break;
case 'month' :
$format = 'F Y';
$date = date('Y-m-d', strtotime($date));
break;
default :
$format = get_option('date_format');
}
return $prefix . date_i18n($format, strtotime($date));
}
/**
* Format time to show in widget
*
* @param int $time
* time in seconds
* @return string formatted time
*/
protected function timeFormat($time)
{
return floor($time / 3600) . 'h ' . floor(($time % 3600) / 60) . 'm ' . floor(($time % 3600) % 60) . 's';
}
/**
* Convert Piwik range into meaningful text
*
* @return string range description
*/
public function rangeName()
{
switch ($this->parameter ['date']) {
case 'last90' :
return __('last 90 days', 'wp-piwik');
case 'last60' :
return __('last 60 days', 'wp-piwik');
case 'last30' :
return __('last 30 days', 'wp-piwik');
case 'last12' :
return __('last 12 ' . $this->parameter ['period'] . 's', 'wp-piwik');
default :
return $this->parameter ['date'];
}
}
/**
* Get the widget name
*
* @return string widget name
*/
public function getName()
{
return str_replace('\\', '-', get_called_class());
}
/**
* Display a pie chart
*
* @param
* array chart data array(array(0 => name, 1 => value))
*/
public function pieChart($data)
{
$labels = '';
$values = '';
foreach ($data as $key => $dataSet) {
$labels .= '"' . htmlentities($dataSet [0]) . '", ';
$values .= htmlentities($dataSet [1]) . ', ';
if ($key == 'Others') break;
}
?>
<div>
<canvas id="<?php echo 'wp-piwik_stats_' . $this->getName() . '_graph' ?>"></canvas>
</div>
<script>
new Chart(
document.getElementById('<?php echo 'wp-piwik_stats_' . $this->getName() . '_graph'; ?>'),
{
type: 'pie',
data: {
labels: [<?php echo $labels ?>],
datasets: [
{
label: '',
data: [<?php echo $values; ?>],
backgroundColor: [
'#4dc9f6',
'#f67019',
'#f53794',
'#537bc4',
'#acc236',
'#166a8f',
'#00a950',
'#58595b',
'#8549ba'
]
}
]
},
options: {
radius:"90%"
}
}
);
</script>
<?php
}
/**
* Return an array value by key, return '-' if not set
*
* @param array $array
* array to get a value from
* @param string $key
* key of the value to get from array
* @return string found value or '-' as a placeholder
*/
protected function value($array, $key)
{
return (isset ($array [$key]) ? $array [$key] : '-');
}
<?php
namespace WP_Piwik;
use WP_Piwik;
/**
* Abstract widget class
*
* @author Andr&eacute; Br&auml;kling
* @package WP_Piwik
*/
abstract class Widget
{
/**
*
* @var WP_Piwik
*/
protected static $wpPiwik;
/**
* @var Settings
*/
protected static $settings;
protected $isShortcode = false, $method = '', $title = '', $context = 'side', $priority = 'core', $parameter = array(), $apiID = array(), $pageId = 'dashboard', $blogId = null, $name = 'Value', $limit = 10, $content = '', $output = '';
/**
* Widget constructor
*
* @param WP_Piwik $wpPiwik
* current WP-Piwik object
* @param Settings $settings
* current WP-Piwik settings
* @param string $pageId
* WordPress page ID (default: dashboard)
* @param string $context
* WordPress meta box context (defualt: side)
* @param string $priority
* WordPress meta box priority (default: default)
* @param array $params
* widget parameters (default: empty array)
* @param boolean $isShortcode
* is the widget shown inline? (default: false)
*/
public function __construct($wpPiwik, $settings, $pageId = 'dashboard', $context = 'side', $priority = 'default', $params = array(), $isShortcode = false)
{
self::$wpPiwik = $wpPiwik;
self::$settings = $settings;
$this->pageId = $pageId;
$this->context = $context;
$this->priority = $priority;
if (self::$settings->checkNetworkActivation() && function_exists('is_super_admin') && is_super_admin() && isset ($_GET ['wpmu_show_stats'])) {
switch_to_blog(( int )$_GET ['wpmu_show_stats']);
$this->blogId = get_current_blog_id();
restore_current_blog();
}
$this->isShortcode = $isShortcode;
$prefix = ($this->pageId == 'dashboard' ? self::$settings->getGlobalOption('plugin_display_name') . ' - ' : '');
$this->configure($prefix, $params);
if (is_array($this->method))
foreach ($this->method as $method) {
$this->apiID [$method] = Request::register($method, $this->parameter);
self::$wpPiwik->log("Register request: " . $this->apiID [$method]);
}
else {
$this->apiID [$this->method] = Request::register($this->method, $this->parameter);
self::$wpPiwik->log("Register request: " . $this->apiID [$this->method]);
}
if ($this->isShortcode)
return;
add_meta_box($this->getName(), $this->title, array(
$this,
'show'
), $pageId, $this->context, $this->priority);
}
/**
* Conifguration dummy method
*
* @param string $prefix
* metabox title prefix (default: empty)
* @param array $params
* widget parameters (default: empty array)
*/
protected function configure($prefix = '', $params = array())
{
}
/**
* Default show widget method, handles default Piwik output
*/
public function show()
{
$response = self::$wpPiwik->request($this->apiID [$this->method]);
if (!empty ($response ['result']) && $response ['result'] == 'error')
$this->out('<strong>' . __('Piwik error', 'wp-piwik') . ':</strong> ' . htmlentities($response ['message'], ENT_QUOTES, 'utf-8'));
else {
if (isset ($response [0] ['nb_uniq_visitors']))
$unique = 'nb_uniq_visitors';
else
$unique = 'sum_daily_nb_uniq_visitors';
$tableHead = array(
'label' => __($this->name, 'wp-piwik')
);
$tableHead [$unique] = __('Unique', 'wp-piwik');
if (isset ($response [0] ['nb_visits']))
$tableHead ['nb_visits'] = __('Visits', 'wp-piwik');
if (isset ($response [0] ['nb_hits']))
$tableHead ['nb_hits'] = __('Hits', 'wp-piwik');
if (isset ($response [0] ['nb_actions']))
$tableHead ['nb_actions'] = __('Actions', 'wp-piwik');
$tableBody = array();
$count = 0;
if (is_array($response))
foreach ($response as $rowKey => $row) {
$count++;
$tableBody [$rowKey] = array();
foreach ($tableHead as $key => $value)
$tableBody [$rowKey] [] = isset ($row [$key]) ? $row [$key] : '-';
if ($count == 10)
break;
}
$this->table($tableHead, $tableBody, null);
}
}
/**
* Display or store shortcode output
*/
protected function out($output)
{
if ($this->isShortcode)
$this->output .= $output;
else echo $output;
}
/**
* Return shortcode output
*/
public function get()
{
return $this->output;
}
/**
* Display a HTML table
*
* @param array $thead
* table header content (array of cells)
* @param array $tbody
* table body content (array of rows)
* @param array $tfoot
* table footer content (array of cells)
* @param string $class
* CSSclass name to apply on table sections
* @param string $javaScript
* array of javascript code to apply on body rows
*/
protected function table($thead, $tbody = array(), $tfoot = array(), $class = false, $javaScript = array(), $classes = array())
{
$this->out('<div class="table"><table class="widefat wp-piwik-table">');
if ($this->isShortcode && $this->title) {
$colspan = !empty ($tbody) ? count($tbody[0]) : 2;
$this->out('<tr><th colspan="' . $colspan . '">' . $this->title . '</th></tr>');
}
if (!empty ($thead))
$this->tabHead($thead, $class);
if (!empty ($tbody))
$this->tabBody($tbody, $class, $javaScript, $classes);
else
$this->out('<tr><td colspan="10">' . __('No data available.', 'wp-piwik') . '</td></tr>');
if (!empty ($tfoot))
$this->tabFoot($tfoot, $class);
$this->out('</table></div>');
}
/**
* Display a HTML table header
*
* @param array $thead
* array of cells
* @param string $class
* CSS class to apply
*/
private function tabHead($thead, $class = false)
{
$this->out('<thead' . ($class ? ' class="' . $class . '"' : '') . '><tr>');
$count = 0;
foreach ($thead as $value)
$this->out('<th' . ($count++ ? ' class="right"' : '') . '>' . $value . '</th>');
$this->out('</tr></thead>');
}
/**
* Display a HTML table body
*
* @param array $tbody
* array of rows, each row containing an array of cells
* @param string $class
* CSS class to apply
* @param array $javaScript
* array of javascript code to apply (one item per row)
*/
private function tabBody($tbody, $class = "", $javaScript = array(), $classes = array())
{
$this->out('<tbody' . ($class ? ' class="' . $class . '"' : '') . '>');
foreach ($tbody as $key => $trow)
$this->tabRow($trow, isset($javaScript [$key]) ? $javaScript [$key] : '', isset ($classes [$key]) ? $classes [$key] : '');
$this->out('</tbody>');
}
/**
* Display a HTML table footer
*
* @param array $tfoor
* array of cells
* @param string $class
* CSS class to apply
*/
private function tabFoot($tfoot, $class = false)
{
$this->out('<tfoot' . ($class ? ' class="' . $class . '"' : '') . '><tr>');
$count = 0;
foreach ($tfoot as $value)
$this->out('<td' . ($count++ ? ' class="right"' : '') . '>' . $value . '</td>');
$this->out('</tr></tfoot>');
}
/**
* Display a HTML table row
*
* @param array $trow
* array of cells
* @param string $javaScript
* javascript code to apply
*/
private function tabRow($trow, $javaScript = '', $class = '')
{
$this->out('<tr' . (!empty ($javaScript) ? ' onclick="' . $javaScript . '"' : '') . (!empty ($class) ? ' class="' . $class . '"' : '') . '>');
$count = 0;
foreach ($trow as $tcell)
$this->out('<td' . ($count++ ? ' class="right"' : '') . '>' . $tcell . '</td>');
$this->out('</tr>');
}
/**
* Get the current request's Piwik time settings
*
* @return array time settings: period => Piwik period, date => requested date, description => time description to show in widget title
*/
protected function getTimeSettings()
{
switch (self::$settings->getGlobalOption('default_date')) {
case 'today' :
$period = 'day';
$date = 'today';
$description = __('today', 'wp-piwik');
break;
case 'current_month' :
$period = 'month';
$date = 'today';
$description = __('current month', 'wp-piwik');
break;
case 'last_month' :
$period = 'month';
$date = date("Y-m-d", strtotime("last day of previous month"));
$description = __('last month', 'wp-piwik');
break;
case 'current_week' :
$period = 'week';
$date = 'today';
$description = __('current week', 'wp-piwik');
break;
case 'last_week' :
$period = 'week';
$date = date("Y-m-d", strtotime("-1 week"));
$description = __('last week', 'wp-piwik');
break;
case 'yesterday' :
$period = 'day';
$date = 'yesterday';
$description = __('yesterday', 'wp-piwik');
break;
default :
break;
}
return array(
'period' => $period,
'date' => isset ($_GET ['date']) ? ( int )$_GET ['date'] : $date,
'description' => isset ($_GET ['date']) ? $this->dateFormat($_GET ['date'], $period) : $description
);
}
/**
* Format a date to show in widget
*
* @param string $date
* date string
* @param string $period
* Piwik period
* @return string formatted date
*/
protected function dateFormat($date, $period = 'day')
{
$prefix = '';
switch ($period) {
case 'week' :
$prefix = __('week', 'wp-piwik') . ' ';
$format = 'W/Y';
break;
case 'short_week' :
$format = 'W';
break;
case 'month' :
$format = 'F Y';
$date = date('Y-m-d', strtotime($date));
break;
default :
$format = get_option('date_format');
}
return $prefix . date_i18n($format, strtotime($date));
}
/**
* Format time to show in widget
*
* @param int $time
* time in seconds
* @return string formatted time
*/
protected function timeFormat($time)
{
return floor($time / 3600) . 'h ' . floor(($time % 3600) / 60) . 'm ' . floor(($time % 3600) % 60) . 's';
}
/**
* Convert Piwik range into meaningful text
*
* @return string range description
*/
public function rangeName()
{
switch ($this->parameter ['date']) {
case 'last90' :
return __('last 90 days', 'wp-piwik');
case 'last60' :
return __('last 60 days', 'wp-piwik');
case 'last30' :
return __('last 30 days', 'wp-piwik');
case 'last12' :
return __('last 12 ' . $this->parameter ['period'] . 's', 'wp-piwik');
default :
return $this->parameter ['date'];
}
}
/**
* Get the widget name
*
* @return string widget name
*/
public function getName()
{
return str_replace('\\', '-', get_called_class());
}
/**
* Display a pie chart
*
* @param
* array chart data array(array(0 => name, 1 => value))
*/
public function pieChart($data)
{
$labels = '';
$values = '';
foreach ($data as $key => $dataSet) {
$labels .= '"' . htmlentities($dataSet [0]) . '", ';
$values .= htmlentities($dataSet [1]) . ', ';
if ($key == 'Others') break;
}
?>
<div>
<canvas id="<?php echo 'wp-piwik_stats_' . $this->getName() . '_graph' ?>"></canvas>
</div>
<script>
new Chart(
document.getElementById('<?php echo 'wp-piwik_stats_' . $this->getName() . '_graph'; ?>'),
{
type: 'pie',
data: {
labels: [<?php echo $labels ?>],
datasets: [
{
label: '',
data: [<?php echo $values; ?>],
backgroundColor: [
'#4dc9f6',
'#f67019',
'#f53794',
'#537bc4',
'#acc236',
'#166a8f',
'#00a950',
'#58595b',
'#8549ba'
]
}
]
},
options: {
radius:"90%"
}
}
);
</script>
<?php
}
/**
* Return an array value by key, return '-' if not set
*
* @param array $array
* array to get a value from
* @param string $key
* key of the value to get from array
* @return string found value or '-' as a placeholder
*/
protected function value($array, $key)
{
return (isset ($array [$key]) ? $array [$key] : '-');
}
}

View File

@ -1,31 +1,38 @@
<?php
namespace WP_Piwik\Widget;
namespace WP_Piwik\Widget;
class OptOut extends \WP_Piwik\Widget {
public $className = __CLASS__;
protected function configure($prefix = '', $params = array()) {
$this->parameter = $params;
}
class OptOut extends \WP_Piwik\Widget
{
public function show() {
$protocol = (isset ( $_SERVER ['HTTPS'] ) && $_SERVER ['HTTPS'] != 'off') ? 'https' : 'http';
switch (self::$settings->getGlobalOption ( 'piwik_mode' )) {
case 'php' :
$PIWIK_URL = $protocol . ':' . self::$settings->getGlobalOption ( 'proxy_url' );
break;
case 'cloud' :
$PIWIK_URL = 'https://' . self::$settings->getGlobalOption ( 'piwik_user' ) . '.innocraft.cloud/';
break;
case 'cloud-matomo':
$PIWIK_URL = 'https://' . self::$settings->getGlobalOption ( 'matomo_user' ) . '.matomo.cloud/';
break;
default :
$PIWIK_URL = self::$settings->getGlobalOption ( 'piwik_url' );
}
$this->out ( '<iframe frameborder="no" width="'.(isset($this->parameter['width'])?$this->parameter['width']:'').'" height="'.(isset($this->parameter['height'])?$this->parameter['height']:'').'" src="'.$PIWIK_URL.'index.php?module=CoreAdminHome&action=optOut&'.(isset($this->parameter['idsite'])?'idsite='.$this->parameter['idsite'].'&':'').'language='.(isset($this->parameter['language'])?$this->parameter['language']:'en').'"></iframe>' );
}
}
public $className = __CLASS__;
protected function configure($prefix = '', $params = array())
{
$this->parameter = $params;
}
public function show()
{
$protocol = (isset ($_SERVER ['HTTPS']) && $_SERVER ['HTTPS'] != 'off') ? 'https' : 'http';
switch (self::$settings->getGlobalOption('piwik_mode')) {
case 'php' :
$PIWIK_URL = $protocol . ':' . self::$settings->getGlobalOption('proxy_url');
break;
case 'cloud' :
$PIWIK_URL = 'https://' . self::$settings->getGlobalOption('piwik_user') . '.innocraft.cloud/';
break;
case 'cloud-matomo':
$PIWIK_URL = 'https://' . self::$settings->getGlobalOption('matomo_user') . '.matomo.cloud/';
break;
default :
$PIWIK_URL = self::$settings->getGlobalOption('piwik_url');
}
$width = (isset($this->parameter['width']) ? esc_attr($this->parameter['width']) : '');
$height = (isset($this->parameter['height']) ? esc_attr($this->parameter['height']) : '');
$idSite = (isset($this->parameter['idsite']) ? 'idsite=' . (int)$this->parameter['idsite'] . '&' : '');
$language = (isset($this->parameter['language']) ? esc_attr($this->parameter['language']) : 'en');
$this->out('<iframe frameborder="no" width="' . $width . '" height="' . $height . '" src="' . $PIWIK_URL . 'index.php?module=CoreAdminHome&action=optOut&' . $idSite . 'language=' . $language . '"></iframe>');
}
}