updated plugin `Connect Matomo` version 1.0.30

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

View File

@ -0,0 +1,2 @@
.idea/

View File

@ -1,4 +1,4 @@
# WP-Matomo (former WP-Piwik) # Connect Matomo (former WP-Matomo, WP-Piwik)
This [WordPress](https://wordpress.org) plugin adds a [Matomo](http://matomo.org) stats site to your blog's dashboard. It's also able to add the Matomo tracking code to your blog. This [WordPress](https://wordpress.org) plugin adds a [Matomo](http://matomo.org) stats site to your blog's dashboard. It's also able to add the Matomo tracking code to your blog.
@ -6,4 +6,4 @@ This [WordPress](https://wordpress.org) plugin adds a [Matomo](http://matomo.org
To use this plugin you will need your own Matomo instance. If you do not already have a Matomo setup, you have two simple options: use either [self-hosted](http://matomo.org/) or [cloud-hosted](http://matomo.org/hosting/). To use this plugin you will need your own Matomo instance. If you do not already have a Matomo setup, you have two simple options: use either [self-hosted](http://matomo.org/) or [cloud-hosted](http://matomo.org/hosting/).
This repository was created to develop and maintain WP-Matomo (WP-Piwik). Please see the WordPress plugin directory if you like to use this plugin: https://wordpress.org/plugins/wp-piwik/ This repository was created to develop and maintain Connect Matomo (WP-Matomo, WP-Piwik). Please see the WordPress plugin directory if you like to use this plugin: https://wordpress.org/plugins/wp-piwik/

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

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

View File

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

View File

@ -1,31 +1,38 @@
<?php <?php
namespace WP_Piwik\Widget; namespace WP_Piwik\Widget;
class OptOut extends \WP_Piwik\Widget { class OptOut extends \WP_Piwik\Widget
{
public $className = __CLASS__;
protected function configure($prefix = '', $params = array()) {
$this->parameter = $params;
}
public function show() { public $className = __CLASS__;
$protocol = (isset ( $_SERVER ['HTTPS'] ) && $_SERVER ['HTTPS'] != 'off') ? 'https' : 'http';
switch (self::$settings->getGlobalOption ( 'piwik_mode' )) { protected function configure($prefix = '', $params = array())
case 'php' : {
$PIWIK_URL = $protocol . ':' . self::$settings->getGlobalOption ( 'proxy_url' ); $this->parameter = $params;
break; }
case 'cloud' :
$PIWIK_URL = 'https://' . self::$settings->getGlobalOption ( 'piwik_user' ) . '.innocraft.cloud/'; public function show()
break; {
case 'cloud-matomo': $protocol = (isset ($_SERVER ['HTTPS']) && $_SERVER ['HTTPS'] != 'off') ? 'https' : 'http';
$PIWIK_URL = 'https://' . self::$settings->getGlobalOption ( 'matomo_user' ) . '.matomo.cloud/'; switch (self::$settings->getGlobalOption('piwik_mode')) {
break; case 'php' :
default : $PIWIK_URL = $protocol . ':' . self::$settings->getGlobalOption('proxy_url');
$PIWIK_URL = self::$settings->getGlobalOption ( 'piwik_url' ); break;
} case 'cloud' :
$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>' ); $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>');
}
}

View File

@ -1,2 +1,2 @@
<?php <?php
// Nothing to see... // Nothing to see...

View File

@ -2,6 +2,23 @@
display: none; display: none;
} }
.wp-piwik-help-list {
list-style-type: disc;
margin-left: 20px;
}
.wp-piwik-input-row label {
display: block;
}
.wp-piwik-input-row input[type=text], .wp-piwik-input-row input:not([type]) {
width: 70%;
}
.wp-piwik-input-row p {
width: 70%;
}
table.wp-piwik-table th.right, td.right { table.wp-piwik-table th.right, td.right {
text-align: right; text-align: right;
} }

View File

@ -1,2 +1,2 @@
<?php <?php
// Nothing to see... // Nothing to see...

View File

@ -1,2 +1,2 @@
<?php <?php
// Nothing to see... // Nothing to see...

View File

@ -80,6 +80,8 @@ msgid ""
"You are running a WordPress %s blog network (WPMU). WP-Matomo will handle " "You are running a WordPress %s blog network (WPMU). WP-Matomo will handle "
"your sites as different websites." "your sites as different websites."
msgstr "" msgstr ""
"You are running a WordPress %s blog network (WPMU). Connect Matomo will handle "
"your sites as different websites."
#: classes/WP_Piwik/Admin/Settings.php:62 #: classes/WP_Piwik/Admin/Settings.php:62
#, php-format #, php-format
@ -87,6 +89,8 @@ msgid ""
"WP-Matomo %s was not able to connect to Matomo using your configuration. Check " "WP-Matomo %s was not able to connect to Matomo using your configuration. Check "
"the &raquo;Connect to Matomo&laquo; section below." "the &raquo;Connect to Matomo&laquo; section below."
msgstr "" msgstr ""
"Connect Matomo %s was not able to connect to Matomo using your configuration. Check "
"the &raquo;Connect to Matomo&laquo; section below."
#: classes/WP_Piwik/Admin/Settings.php:64 #: classes/WP_Piwik/Admin/Settings.php:64
#, php-format #, php-format
@ -94,6 +98,8 @@ msgid ""
"WP-Matomo %s was not able to connect to Matomo using your configuration. " "WP-Matomo %s was not able to connect to Matomo using your configuration. "
"During connection the following error occured: <br /><code>%s</code>" "During connection the following error occured: <br /><code>%s</code>"
msgstr "" msgstr ""
"Connect Matomo %s was not able to connect to Matomo using your configuration. "
"During connection the following error occured: <br /><code>%s</code>"
#: classes/WP_Piwik/Admin/Settings.php:67 #: classes/WP_Piwik/Admin/Settings.php:67
#, php-format #, php-format
@ -101,6 +107,8 @@ msgid ""
"WP-Matomo %s has to be connected to Matomo first. Check the &raquo;Connect to " "WP-Matomo %s has to be connected to Matomo first. Check the &raquo;Connect to "
"Matomo&laquo; section below." "Matomo&laquo; section below."
msgstr "" msgstr ""
"Connect Matomo %s has to be connected to Matomo first. Check the &raquo;Connect to "
"Matomo&laquo; section below."
#: classes/WP_Piwik/Admin/Settings.php:71 #: classes/WP_Piwik/Admin/Settings.php:71
msgid "Connect to Matomo" msgid "Connect to Matomo"
@ -129,6 +137,10 @@ msgid ""
"To use this you will need your own Matomo instance. If you do not already " "To use this you will need your own Matomo instance. If you do not already "
"have a Matomo setup, you have two simple options: use either" "have a Matomo setup, you have two simple options: use either"
msgstr "" msgstr ""
"Connect Matomo is a WordPress plugin to show a selection of Matomo stats in your "
"WordPress admin dashboard and to add and configure your Matomo tracking code. "
"To use this you will need your own Matomo instance. If you do not already "
"have a Matomo setup, you have two simple options: use either"
#: classes/WP_Piwik/Admin/Settings.php:106 #: classes/WP_Piwik/Admin/Settings.php:106
msgid "a self-hosted Matomo" msgid "a self-hosted Matomo"
@ -147,6 +159,8 @@ msgid ""
"Neither cURL nor fopen are available. So WP-Matomo can not use the HTTP API " "Neither cURL nor fopen are available. So WP-Matomo can not use the HTTP API "
"and not connect to InnoCraft Cloud." "and not connect to InnoCraft Cloud."
msgstr "" msgstr ""
"Neither cURL nor fopen are available. So Connect Matomo can not use the HTTP API "
"and not connect to InnoCraft Cloud."
#: classes/WP_Piwik/Admin/Settings.php:109 #: classes/WP_Piwik/Admin/Settings.php:109
#: classes/WP_Piwik/Template/MetaBoxCustomVars.php:30 #: classes/WP_Piwik/Template/MetaBoxCustomVars.php:30
@ -167,6 +181,8 @@ msgid ""
"This is the default option for a self-hosted Matomo and should work for most " "This is the default option for a self-hosted Matomo and should work for most "
"configurations. WP-Matomo will connect to Matomo using http(s)." "configurations. WP-Matomo will connect to Matomo using http(s)."
msgstr "" msgstr ""
"This is the default option for a self-hosted Matomo and should work for most "
"configurations. Connect Matomo will connect to Matomo using http(s)."
#: classes/WP_Piwik/Admin/Settings.php:111 #: classes/WP_Piwik/Admin/Settings.php:111
#: classes/WP_Piwik/Admin/Settings.php:115 #: classes/WP_Piwik/Admin/Settings.php:115
@ -250,13 +266,16 @@ msgid ""
"Check this to automatically choose your blog from your Matomo sites by URL. " "Check this to automatically choose your blog from your Matomo sites by URL. "
"If your blog is not added to Matomo yet, WP-Matomo will add a new site." "If your blog is not added to Matomo yet, WP-Matomo will add a new site."
msgstr "" msgstr ""
"Check this to automatically choose your blog from your Matomo sites by URL. "
"If your blog is not added to Matomo yet, Connect Matomo will add a new site."
#: classes/WP_Piwik/Admin/Settings.php:131 #: classes/WP_Piwik/Admin/Settings.php:131
#, php-format #, php-format
msgid "" msgid ""
"WP-Matomo %s was not able to get sites with at least view access: <br /><code>" "WP-Matomo %s was not able to get sites with at least view access: <br /><code>"
"%s</code>" "%s</code>"
msgstr "" msgstr "Connect Matomo %s was not able to get sites with at least view access: <br /><code>"
"%s</code>"
#: classes/WP_Piwik/Admin/Settings.php:141 #: classes/WP_Piwik/Admin/Settings.php:141
msgid "Determined site" msgid "Determined site"
@ -400,7 +419,7 @@ msgstr ""
#: classes/WP_Piwik/Admin/Settings.php:195 #: classes/WP_Piwik/Admin/Settings.php:195
msgid "WP-Matomo display name" msgid "WP-Matomo display name"
msgstr "" msgstr "Connect Matomo display name"
#: classes/WP_Piwik/Admin/Settings.php:195 #: classes/WP_Piwik/Admin/Settings.php:195
msgid "Plugin name shown in WordPress." msgid "Plugin name shown in WordPress."
@ -424,6 +443,9 @@ msgid ""
"tracking code to your template files or you use another plugin to add the " "tracking code to your template files or you use another plugin to add the "
"tracking code." "tracking code."
msgstr "" msgstr ""
"Connect Matomo will not add the tracking code. Use this, if you want to add the "
"tracking code to your template files or you use another plugin to add the "
"tracking code."
#: classes/WP_Piwik/Admin/Settings.php:208 #: classes/WP_Piwik/Admin/Settings.php:208
#: classes/WP_Piwik/Admin/Settings.php:211 #: classes/WP_Piwik/Admin/Settings.php:211
@ -778,6 +800,8 @@ msgid ""
"Choose whether WP-Matomo should use cURL or fopen to connect to Matomo in HTTP " "Choose whether WP-Matomo should use cURL or fopen to connect to Matomo in HTTP "
"or Cloud mode." "or Cloud mode."
msgstr "" msgstr ""
"Choose whether Connect Matomo should use cURL or fopen to connect to Matomo in HTTP "
"or Cloud mode."
#: classes/WP_Piwik/Admin/Settings.php:305 #: classes/WP_Piwik/Admin/Settings.php:305
msgid "HTTP method" msgid "HTTP method"
@ -795,7 +819,7 @@ msgstr ""
#: classes/WP_Piwik/Admin/Settings.php:308 #: classes/WP_Piwik/Admin/Settings.php:308
msgid "Choose whether WP-Matomo should use POST or GET in HTTP or Cloud mode." msgid "Choose whether WP-Matomo should use POST or GET in HTTP or Cloud mode."
msgstr "" msgstr "Choose whether Connect Matomo should use POST or GET in HTTP or Cloud mode."
#: classes/WP_Piwik/Admin/Settings.php:310 #: classes/WP_Piwik/Admin/Settings.php:310
msgid "Disable time limit" msgid "Disable time limit"
@ -906,11 +930,11 @@ msgstr ""
#: classes/WP_Piwik/Admin/Settings.php:338 #: classes/WP_Piwik/Admin/Settings.php:338
msgid "Show always if WP-Matomo is updated" msgid "Show always if WP-Matomo is updated"
msgstr "" msgstr "Show always if Connect Matomo is updated"
#: classes/WP_Piwik/Admin/Settings.php:339 #: classes/WP_Piwik/Admin/Settings.php:339
msgid "Show only if WP-Matomo is updated and settings were changed" msgid "Show only if WP-Matomo is updated and settings were changed"
msgstr "" msgstr "Show only if Connect Matomo is updated and settings were changed"
#: classes/WP_Piwik/Admin/Settings.php:341 #: classes/WP_Piwik/Admin/Settings.php:341
msgid "Choose if you want to get an update notice if WP-Matomo is updated." msgid "Choose if you want to get an update notice if WP-Matomo is updated."
@ -1004,6 +1028,9 @@ msgid ""
"commendation, feature requests and bug reports! You help me to make WP-Matomo " "commendation, feature requests and bug reports! You help me to make WP-Matomo "
"much better." "much better."
msgstr "" msgstr ""
"Thank you very much, all users who send me mails containing criticism, "
"commendation, feature requests and bug reports! You help me to make Connect Matomo "
"much better."
#: classes/WP_Piwik/Admin/Settings.php:565 #: classes/WP_Piwik/Admin/Settings.php:565
msgid "" msgid ""

View File

@ -1,39 +1,39 @@
<?php <?php
$wpRootDir = isset($wpRootDir)?$wpRootDir:'../../../../'; $wpRootDir = isset($wpRootDir)?$wpRootDir:'../../../../';
require ($wpRootDir.'wp-load.php'); require ($wpRootDir.'wp-load.php');
require_once ('../classes/WP_Piwik/Settings.php'); require_once ('../classes/WP_Piwik/Settings.php');
require_once ('../classes/WP_Piwik/Logger.php'); require_once ('../classes/WP_Piwik/Logger.php');
require_once ('../classes/WP_Piwik/Logger/Dummy.php'); require_once ('../classes/WP_Piwik/Logger/Dummy.php');
$logger = new WP_Piwik\Logger\Dummy ( __CLASS__ ); $logger = new WP_Piwik\Logger\Dummy ( __CLASS__ );
$settings = new WP_Piwik\Settings ( $logger ); $settings = new WP_Piwik\Settings ( $logger );
$protocol = (isset ( $_SERVER ['HTTPS'] ) && $_SERVER ['HTTPS'] != 'off') ? 'https' : 'http'; $protocol = (isset ( $_SERVER ['HTTPS'] ) && $_SERVER ['HTTPS'] != 'off') ? 'https' : 'http';
switch ($settings->getGlobalOption ( 'piwik_mode' )) { switch ($settings->getGlobalOption ( 'piwik_mode' )) {
case 'php' : case 'php' :
$PIWIK_URL = $settings->getGlobalOption ( 'proxy_url' ); $PIWIK_URL = $settings->getGlobalOption ( 'proxy_url' );
break; break;
case 'cloud' : case 'cloud' :
$PIWIK_URL = 'https://' . $settings->getGlobalOption ( 'piwik_user' ) . '.innocraft.cloud/'; $PIWIK_URL = 'https://' . $settings->getGlobalOption ( 'piwik_user' ) . '.innocraft.cloud/';
break; break;
case 'cloud-matomo' : case 'cloud-matomo' :
$PIWIK_URL = 'https://' . $settings->getGlobalOption ( 'matomo_user' ) . '.matomo.cloud/'; $PIWIK_URL = 'https://' . $settings->getGlobalOption ( 'matomo_user' ) . '.matomo.cloud/';
break; break;
default : default :
$PIWIK_URL = $settings->getGlobalOption ( 'piwik_url' ); $PIWIK_URL = $settings->getGlobalOption ( 'piwik_url' );
} }
if (substr ( $PIWIK_URL, 0, 2 ) == '//') if (substr ( $PIWIK_URL, 0, 2 ) == '//')
$PIWIK_URL = $protocol . ':' . $PIWIK_URL; $PIWIK_URL = $protocol . ':' . $PIWIK_URL;
$TOKEN_AUTH = $settings->getGlobalOption ( 'piwik_token' ); $TOKEN_AUTH = $settings->getGlobalOption ( 'piwik_token' );
$timeout = $settings->getGlobalOption ( 'connection_timeout' ); $timeout = $settings->getGlobalOption ( 'connection_timeout' );
$useCurl = ( $useCurl = (
(function_exists('curl_init') && ini_get('allow_url_fopen') && $settings->getGlobalOption('http_connection') == 'curl') || (function_exists('curl_init') && !ini_get('allow_url_fopen')) (function_exists('curl_init') && ini_get('allow_url_fopen') && $settings->getGlobalOption('http_connection') == 'curl') || (function_exists('curl_init') && !ini_get('allow_url_fopen'))
); );
$settings->getGlobalOption ( 'http_connection' ); $settings->getGlobalOption ( 'http_connection' );
ini_set ( 'display_errors', 0 ); ini_set ( 'display_errors', 0 );

View File

@ -1,2 +1,2 @@
<?php <?php
// Nothing to see... // Nothing to see...

View File

@ -1,9 +1,9 @@
=== WP-Matomo Integration (WP-Piwik) === === Connect Matomo (WP-Matomo, WP-Piwik) ===
Contributors: Braekling Contributors: Braekling
Requires at least: 5.0 Requires at least: 5.0
Tested up to: 6.2 Tested up to: 6.3
Stable tag: 1.0.28 Stable tag: 1.0.30
Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=6046779 Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=6046779
Tags: matomo, tracking, statistics, stats, analytics Tags: matomo, tracking, statistics, stats, analytics
@ -70,9 +70,11 @@ You can get a more detailed description here: https://matomo.org/blog/2015/05/wo
First, please make sure your configuration is valid, e.g., if you are using the right Matomo URL (see description above). Then, go to the "Support" tab and run the test script. This test script will try to get some information from Matomo and shows the full response. Usually, the response output gives a clear hint what's wrong: First, please make sure your configuration is valid, e.g., if you are using the right Matomo URL (see description above). Then, go to the "Support" tab and run the test script. This test script will try to get some information from Matomo and shows the full response. Usually, the response output gives a clear hint what's wrong:
The response output contains... The response output contains...
* **bool(false)** and **HTTP/1.1 403 Forbidden**: WP-Matomo is not allowed to connect to Matomo. Please check your Matomo server's configuration. Maybe you are using a password protection via .htaccess or you are blocking requests from localhost/127.0.0.1. If you arent sure about this, please contact your web hoster for support. - **bool(false)** and **HTTP/1.1 403 Forbidden**: WP-Matomo is not allowed to connect to Matomo. Please check your Matomo server's configuration. Maybe you are using a password protection via .htaccess or you are blocking requests from localhost/127.0.0.1. If you arent sure about this, please contact your web hoster for support.
* **bool(false)** and **HTTP/1.1 404 Not Found**: The Matomo URL is wrong. Try to copy & paste the URL you use to access Matomo itself via browser. - **bool(false)** and **HTTP/1.1 404 Not Found**: The Matomo URL is wrong. Try to copy & paste the URL you use to access Matomo itself via browser.
* **bool(false)** and no further HTTP response code: The Matomo server does not respond. Very often, this is caused by firewall or mod_security settings. Check your server logfiles to get further information. If you arent sure about this, please contact your web hoster for support. - **bool(false)** and no further HTTP response code: The Matomo server does not respond. Very often, this is caused by firewall or mod_security settings. Check your server logfiles to get further information. If you arent sure about this, please contact your web hoster for support.
If this does not help as well, feel free to open a [topic in the support forum](https://wordpress.org/support/plugin/wp-piwik/). Please share all available information including the test script result, if possible.
= PHP Compatibility Checker reports PHP7 compatbility issues with WP-Matomo. = = PHP Compatibility Checker reports PHP7 compatbility issues with WP-Matomo. =
@ -143,6 +145,16 @@ Add WP-Matomo to your /wp-content/plugins folder and enable it as [Network Plugi
== Changelog == == Changelog ==
= 1.0.30 =
* Fix settings behavior
* Fix auto configuration in PHP API mode
* Fix Opt-Out shortcode language attribute
* Remove deprecated dynamic property (PHP 8.2)
= 1.0.29 =
* Rename plugin to "Connect Matomo"
* Fix a XSS vulnerability
= 1.0.28 = = 1.0.28 =
* Encode plugin display name * Encode plugin display name
* Option to set requireConsent or requireCookieConsent * Option to set requireConsent or requireCookieConsent

View File

@ -1,41 +1,41 @@
<?php <?php
// Get & delete old version's options // Get & delete old version's options
if (self::$settings->checkNetworkActivation ()) { if (self::$settings->checkNetworkActivation ()) {
$oldGlobalOptions = get_site_option ( 'wp-piwik_global-settings', array () ); $oldGlobalOptions = get_site_option ( 'wp-piwik_global-settings', array () );
delete_site_option('wp-piwik_global-settings'); delete_site_option('wp-piwik_global-settings');
} else { } else {
$oldGlobalOptions = get_option ( 'wp-piwik_global-settings', array () ); $oldGlobalOptions = get_option ( 'wp-piwik_global-settings', array () );
delete_option('wp-piwik_global-settings'); delete_option('wp-piwik_global-settings');
} }
$oldOptions = get_option ( 'wp-piwik_settings', array () ); $oldOptions = get_option ( 'wp-piwik_settings', array () );
delete_option('wp-piwik_settings'); delete_option('wp-piwik_settings');
if (self::$settings->checkNetworkActivation ()) { if (self::$settings->checkNetworkActivation ()) {
global $wpdb; global $wpdb;
$aryBlogs = \WP_Piwik\Settings::getBlogList(); $aryBlogs = \WP_Piwik\Settings::getBlogList();
if (is_array($aryBlogs)) if (is_array($aryBlogs))
foreach ($aryBlogs as $aryBlog) { foreach ($aryBlogs as $aryBlog) {
$oldOptions = get_blog_option ( $aryBlog['blog_id'], 'wp-piwik_settings', array () ); $oldOptions = get_blog_option ( $aryBlog['blog_id'], 'wp-piwik_settings', array () );
if (!$this->isConfigured()) if (!$this->isConfigured())
foreach ( $oldOptions as $key => $value ) foreach ( $oldOptions as $key => $value )
self::$settings->setOption ( $key, $value, $aryBlog['blog_id'] ); self::$settings->setOption ( $key, $value, $aryBlog['blog_id'] );
delete_blog_option($aryBlog['blog_id'], 'wp-piwik_settings'); delete_blog_option($aryBlog['blog_id'], 'wp-piwik_settings');
} }
} }
if (!$this->isConfigured()) { if (!$this->isConfigured()) {
if (!$oldGlobalOptions['add_tracking_code']) $oldGlobalOptions['track_mode'] = 'disabled'; if (!$oldGlobalOptions['add_tracking_code']) $oldGlobalOptions['track_mode'] = 'disabled';
elseif (!$oldGlobalOptions['track_mode']) $oldGlobalOptions['track_mode'] = 'default'; elseif (!$oldGlobalOptions['track_mode']) $oldGlobalOptions['track_mode'] = 'default';
elseif ($oldGlobalOptions['track_mode'] == 1) $oldGlobalOptions['track_mode'] = 'js'; elseif ($oldGlobalOptions['track_mode'] == 1) $oldGlobalOptions['track_mode'] = 'js';
elseif ($oldGlobalOptions['track_mode'] == 2) $oldGlobalOptions['track_mode'] = 'proxy'; elseif ($oldGlobalOptions['track_mode'] == 2) $oldGlobalOptions['track_mode'] = 'proxy';
// Store old values in new settings // Store old values in new settings
foreach ( $oldGlobalOptions as $key => $value ) foreach ( $oldGlobalOptions as $key => $value )
self::$settings->setGlobalOption ( $key, $value ); self::$settings->setGlobalOption ( $key, $value );
foreach ( $oldOptions as $key => $value ) foreach ( $oldOptions as $key => $value )
self::$settings->setOption ( $key, $value ); self::$settings->setOption ( $key, $value );
} }
self::$settings->save (); self::$settings->save ();

View File

@ -0,0 +1,4 @@
<?php
self::$settings->setGlobalOption('plugin_display_name', "Connect Matomo");
self::$settings->save ();

View File

@ -1,9 +1,9 @@
<?php <?php
$aryWPMUConfig = get_site_option ( 'wpmu-piwik_global-settings', false ); $aryWPMUConfig = get_site_option ( 'wpmu-piwik_global-settings', false );
if (self::$settings->checkNetworkActivation () && $aryWPMUConfig) { if (self::$settings->checkNetworkActivation () && $aryWPMUConfig) {
foreach ( $aryWPMUConfig as $key => $value ) foreach ( $aryWPMUConfig as $key => $value )
self::$settings->setGlobalOption ( $key, $value ); self::$settings->setGlobalOption ( $key, $value );
delete_site_option ( 'wpmu-piwik_global-settings' ); delete_site_option ( 'wpmu-piwik_global-settings' );
self::$settings->setGlobalOption ( 'auto_site_config', true ); self::$settings->setGlobalOption ( 'auto_site_config', true );
} else } else
self::$settings->setGlobalOption ( 'auto_site_config', false ); self::$settings->setGlobalOption ( 'auto_site_config', false );

View File

@ -1,5 +1,5 @@
<?php <?php
if (self::$settings->getGlobalOption ( 'track_compress' )) if (self::$settings->getGlobalOption ( 'track_compress' ))
self::$settings->setGlobalOption ( 'track_mode', 1 ); self::$settings->setGlobalOption ( 'track_mode', 1 );
else else
self::$settings->setGlobalOption ( 'track_mode', 0 ); self::$settings->setGlobalOption ( 'track_mode', 0 );

View File

@ -1,10 +1,10 @@
<?php <?php
$aryRemoveOptions = array ( $aryRemoveOptions = array (
'wp-piwik_siteid', 'wp-piwik_siteid',
'wp-piwik_404', 'wp-piwik_404',
'wp-piwik_scriptupdate', 'wp-piwik_scriptupdate',
'wp-piwik_dashboardid', 'wp-piwik_dashboardid',
'wp-piwik_jscode' 'wp-piwik_jscode'
); );
foreach ( $aryRemoveOptions as $strRemoveOption ) foreach ( $aryRemoveOptions as $strRemoveOption )
delete_option ( $strRemoveOption ); delete_option ( $strRemoveOption );

View File

@ -1,83 +1,83 @@
<?php <?php
/* /*
Plugin Name: WP-Matomo Integration Plugin Name: Connect Matomo
Plugin URI: http://wordpress.org/extend/plugins/wp-piwik/ Plugin URI: http://wordpress.org/extend/plugins/wp-piwik/
Description: Adds Matomo statistics to your WordPress dashboard and is also able to add the Matomo Tracking Code to your blog. Description: Adds Matomo statistics to your WordPress dashboard and is also able to add the Matomo Tracking Code to your blog.
Version: 1.0.28 Version: 1.0.30
Author: Andr&eacute; Br&auml;kling Author: Andr&eacute; Br&auml;kling
Author URI: https://www.braekling.de Author URI: https://www.braekling.de
Text Domain: wp-piwik Text Domain: wp-piwik
Domain Path: /languages Domain Path: /languages
License: GPL3 License: GPL3
****************************************************************************************** ******************************************************************************************
Copyright (C) 2009-today Andre Braekling (email: webmaster@braekling.de) Copyright (C) 2009-today Andre Braekling (email: webmaster@braekling.de)
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
at your option) any later version. at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************************/ *******************************************************************************************/
if (! function_exists ( 'add_action' )) { if (! function_exists ( 'add_action' )) {
header ( 'Status: 403 Forbidden' ); header ( 'Status: 403 Forbidden' );
header ( 'HTTP/1.1 403 Forbidden' ); header ( 'HTTP/1.1 403 Forbidden' );
exit (); exit ();
} }
if (! defined ( 'NAMESPACE_SEPARATOR' )) if (! defined ( 'NAMESPACE_SEPARATOR' ))
define ( 'NAMESPACE_SEPARATOR', '\\' ); define ( 'NAMESPACE_SEPARATOR', '\\' );
/** /**
* Define WP-Piwik autoloader * Define WP-Piwik autoloader
* *
* @param string $class * @param string $class
* class name * class name
*/ */
function wp_piwik_autoloader($class) { function wp_piwik_autoloader($class) {
if (substr ( $class, 0, 9 ) == 'WP_Piwik' . NAMESPACE_SEPARATOR) { if (substr ( $class, 0, 9 ) == 'WP_Piwik' . NAMESPACE_SEPARATOR) {
$class = str_replace ( '.', '', str_replace ( NAMESPACE_SEPARATOR, DIRECTORY_SEPARATOR, substr ( $class, 9 ) ) ); $class = str_replace ( '.', '', str_replace ( NAMESPACE_SEPARATOR, DIRECTORY_SEPARATOR, substr ( $class, 9 ) ) );
require_once ('classes' . DIRECTORY_SEPARATOR . 'WP_Piwik' . DIRECTORY_SEPARATOR . $class . '.php'); require_once ('classes' . DIRECTORY_SEPARATOR . 'WP_Piwik' . DIRECTORY_SEPARATOR . $class . '.php');
} }
} }
/** /**
* Show notice about outdated PHP version * Show notice about outdated PHP version
*/ */
function wp_piwik_phperror() { function wp_piwik_phperror() {
echo '<div class="error"><p>'; echo '<div class="error"><p>';
printf ( __ ( 'WP-Matomo requires at least PHP 5.3. You are using the deprecated version %s. Please update PHP to use WP-Matomo.', 'wp-piwik' ), PHP_VERSION ); printf ( __ ( 'WP-Matomo requires at least PHP 5.3. You are using the deprecated version %s. Please update PHP to use WP-Matomo.', 'wp-piwik' ), PHP_VERSION );
echo '</p></div>'; echo '</p></div>';
} }
function wp_piwik_load_textdomain() { function wp_piwik_load_textdomain() {
load_plugin_textdomain( 'wp-piwik', false, plugin_basename( dirname( __FILE__ ) ) . DIRECTORY_SEPARATOR . 'languages' . DIRECTORY_SEPARATOR ); load_plugin_textdomain( 'wp-piwik', false, plugin_basename( dirname( __FILE__ ) ) . DIRECTORY_SEPARATOR . 'languages' . DIRECTORY_SEPARATOR );
} }
add_action( 'plugins_loaded', 'wp_piwik_load_textdomain' ); add_action( 'plugins_loaded', 'wp_piwik_load_textdomain' );
if (version_compare ( PHP_VERSION, '5.3.0', '<' )) if (version_compare ( PHP_VERSION, '5.3.0', '<' ))
add_action ( 'admin_notices', 'wp_piwik_phperror' ); add_action ( 'admin_notices', 'wp_piwik_phperror' );
else { else {
define ( 'WP_PIWIK_PATH', dirname ( __FILE__ ) . DIRECTORY_SEPARATOR ); define ( 'WP_PIWIK_PATH', dirname ( __FILE__ ) . DIRECTORY_SEPARATOR );
require_once (WP_PIWIK_PATH . 'config.php'); require_once (WP_PIWIK_PATH . 'config.php');
require_once (WP_PIWIK_PATH . 'classes' . DIRECTORY_SEPARATOR . 'WP_Piwik.php'); require_once (WP_PIWIK_PATH . 'classes' . DIRECTORY_SEPARATOR . 'WP_Piwik.php');
spl_autoload_register ( 'wp_piwik_autoloader' ); spl_autoload_register ( 'wp_piwik_autoloader' );
$GLOBALS ['wp-piwik_debug'] = false; $GLOBALS ['wp-piwik_debug'] = false;
if (class_exists ( 'WP_Piwik' )) if (class_exists ( 'WP_Piwik' ))
add_action( 'init', 'wp_piwik_loader' ); add_action( 'init', 'wp_piwik_loader' );
} }
function wp_piwik_loader() { function wp_piwik_loader() {
$GLOBALS ['wp-piwik'] = new WP_Piwik (); $GLOBALS ['wp-piwik'] = new WP_Piwik ();
} }