updated plugin Connect Matomo version 1.1.5

This commit is contained in:
2026-06-03 21:28:54 +00:00
committed by Gitium
parent 6e8ffa6f66
commit 1f3438440f
78 changed files with 13800 additions and 5314 deletions

View File

@ -0,0 +1,10 @@
root = true
[*]
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.php]
indent_style = tab
indent_size = 4

View File

@ -1,2 +1,5 @@
.idea/ .idea/
node_modules/
vendor/

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,234 @@
<?php
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
* @package matomo
*/
namespace WP_Piwik;
use LiteSpeed\ESI;
/**
* Performs server side tracking for AI bots.
*
* Normal server side tracking: when no caching plugins or CDNs are being
* used, this class will send tracking requests in the wp_footer hook.
*
* When advanced-cache.php is used: when a caching plugin creates an
* advanced-cache.php file that WordPress uses, tracking must be done
* through the standalone script in misc/track_ai_bot.php. This script
* must be manually added to a user's wp-config.php file, right after
* ABSPATH is defined.
*
* When .htaccess is used: when a caching plugin modifies the .htaccess
* to serve cached files directly, AI bot tracking is not possible.
*
* When a CDN is used: when a CDN is used to serve cached content, AI
* bot tracking can be accomplished through the use of ESI (Edge Side Includes).
* In this case, this class outputs an `<esi:include>` directive that
* loads the misc/track_ai_bot.php script. This technique will only work
* for CDNs that support ESI.
*
* The misc/track_ai_bot.php script uses this class without all of WordPress loaded.
* It can also be loaded outside of WordPress. Because of this, it is important
* that the script and this class use as few total dependencies as possible. Otherwise,
* AI bot tracking reduce the performance of requests to cached content.
*/
class AIBotTracking {
private static $ai_bot_tracked = false;
private static $extensions_to_track = array(
'', // no extension
'htm',
'html',
'php',
);
/**
* @var Settings
*/
private $settings;
/**
* @var Logger
*/
private $logger;
/**
* @var AjaxTracker|null
*/
private $tracker = null;
/**
* @param Settings $settings
* @param Logger $logger
*/
public function __construct( Settings $settings, Logger $logger ) {
$this->settings = $settings;
$this->logger = $logger;
}
public function register_hooks() {
add_action( 'litespeed_init', array( $this, 'litespeed_init' ) );
add_action( 'wp_footer', array( $this, 'do_ai_bot_tracking' ), 999999 );
}
public function litespeed_init() {
if ( class_exists( ESI::class )
&& $this->settings->is_ai_bot_tracking_enabled_via_esi_includes()
) {
ESI::set_has_esi();
}
}
/**
* @param string|null $url
* @return void
*/
public function do_ai_bot_tracking( $url = null ) {
// track AI bots only once per request
if ( self::$ai_bot_tracked ) {
return;
}
self::$ai_bot_tracked = true;
// if using ESI to track, and not within the track_ai_bot.php script, output the appropriate ESI tag
$is_using_esi_to_track = $this->settings->is_ai_bot_tracking_enabled_via_esi_includes();
if (
$is_using_esi_to_track
&& empty( $GLOBALS['WP_PIWIK_IN_ESI'] )
) {
$track_script_url = plugins_url( '/misc/track_ai_bot.php', WP_PIWIK_FILE ) . '?mtm_esi=1&mtm_url=' . rawurlencode( AjaxTracker::getCurrentUrl() );
echo '<esi:include src="' . esc_attr( $track_script_url ) . '" cache-control="no-cache" />';
return;
}
if ( ! $this->is_doing_ai_bot_tracking_this_request() ) {
return;
}
$response_code = http_response_code();
$request_elapsed_ms = null;
// cannot track request time if executed via an esi:include
if (
empty( $GLOBALS['WP_PIWIK_IN_ESI'] )
&& array_key_exists( 'REQUEST_TIME_FLOAT', $_SERVER )
) {
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash
$request_elapsed_ms = (int) ( ( microtime( true ) - floatval( $_SERVER['REQUEST_TIME_FLOAT'] ) ) * 1000 );
}
if ( empty( $response_code ) ) {
$response_code = 200;
}
// phpcs:ignore WordPress.WP.CapitalPDangit.Misspelled
$source = 'WordPress';
if ( empty( $url ) ) {
$url = AjaxTracker::getCurrentUrl();
}
$tracker = $this->get_tracker();
$tracker->setUrl( $url );
// cannot count bytes echo'd so no response size tracked
$tracker->doTrackPageViewIfAIBot( $response_code, null, $request_elapsed_ms, $source );
}
public function should_track_current_page() {
if ( is_admin() ) {
return false;
}
if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
return false;
}
if ( wp_doing_ajax() ) {
return false;
}
if ( empty( $_SERVER['REQUEST_URI'] ) ) {
return false;
}
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$request_path = (string) wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_PATH );
if ( preg_match( '/matomo\.php$/', $request_path ) ) {
return false;
}
if ( $this->is_request_for_file( $request_path ) ) {
return false;
}
return true;
}
private function is_request_for_file( $request_path ) {
if (
! empty( $_SERVER['DOCUMENT_ROOT'] )
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
&& is_dir( wp_unslash( $_SERVER['DOCUMENT_ROOT'] ) . $request_path )
) {
return false;
}
$extension = pathinfo( $request_path, PATHINFO_EXTENSION );
return ! in_array( $extension, self::$extensions_to_track, true );
}
public function is_js_execution_detected() {
return ! empty( $_COOKIE['matomo_has_js'] )
&& '1' === $_COOKIE['matomo_has_js'];
}
private function is_doing_ai_bot_tracking_this_request() {
if ( ! empty( $GLOBALS['WP_PIWIK_IN_ESI'] ) ) {
return true;
}
if ( ! $this->should_track_current_page() ) {
return false;
}
if ( $this->is_js_execution_detected() ) {
return false;
}
$tracker = $this->get_tracker();
// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
if ( ! AjaxTracker::isUserAgentAIBot( $tracker->userAgent ) ) {
return false;
}
if (
! $this->settings->is_ai_bot_tracking_enabled()
|| ! $this->settings->is_tracking_enabled()
) {
return false;
}
return true;
}
private function get_tracker() {
if ( empty( $this->tracker ) ) {
$this->tracker = new AjaxTracker( $this->settings, $this->logger );
$this->tracker->setRequestTimeout( 1 );
}
return $this->tracker;
}
}

View File

@ -1,24 +1,34 @@
<?php <?php
namespace WP_Piwik; namespace WP_Piwik;
abstract class Admin { abstract class Admin {
protected static $wpPiwik, $pageID, $settings; /**
* @var \WP_Piwik
*/
protected static $wp_piwik;
protected static $page_id;
public function __construct($wpPiwik, $settings) { /**
self::$wpPiwik = $wpPiwik; * @var Settings
self::$settings = $settings; */
} protected static $settings;
abstract public function show();
abstract public function printAdminScripts();
public function printAdminStyles() {
wp_enqueue_style('wp-piwik', self::$wpPiwik->getPluginURL().'css/wp-piwik.css', array(), self::$wpPiwik->getPluginVersion());
}
public function onLoad() {}
public function __construct( $wp_piwik, $settings ) {
self::$wp_piwik = $wp_piwik;
self::$settings = $settings;
} }
abstract public function show();
abstract public function print_admin_scripts();
public function print_admin_styles() {
wp_enqueue_style( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'css/wp-piwik.css', array(), self::$wp_piwik->get_plugin_version() );
}
public function on_load() {
// empty
}
}

View File

@ -1,19 +1,16 @@
<?php <?php
namespace WP_Piwik\Admin; namespace WP_Piwik\Admin;
class Network extends \WP_Piwik\Admin\Statistics { class Network extends \WP_Piwik\Admin\Statistics {
public function show() { public function print_admin_scripts() {
parent::show(); $version = self::$wp_piwik->get_plugin_version();
} wp_enqueue_script( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'js/wp-piwik.js', array(), $version, true );
wp_enqueue_script( 'wp-piwik-chartjs', self::$wp_piwik->get_plugin_url() . 'js/chartjs/chart.min.js', array(), $version, false );
public function printAdminScripts() {
wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
wp_enqueue_script ( 'wp-piwik-chartjs', self::$wpPiwik->getPluginURL() . 'js/chartjs/chart.min.js', "3.4.1" );
}
public function onLoad() {
self::$wpPiwik->onloadStatsPage(self::$pageID);
}
} }
public function on_load() {
self::$wp_piwik->onload_stats_page();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -2,111 +2,131 @@
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';
}
/**
* phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
* phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
*/
class Sitebrowser extends \WP_List_Table { class Sitebrowser extends \WP_List_Table {
private $data = array (), $wpPiwik; private $data = array();
public function __construct($wpPiwik) { /**
$this->wpPiwik = $wpPiwik; * @var \WP_Piwik
if( isset($_POST['s']) ){ */
$cnt = $this->prepare_items ($_POST['s']); private $wp_piwik;
} else {
$cnt = $this->prepare_items (); public function __construct( $wp_piwik ) {
} $this->wp_piwik = $wp_piwik;
global $status, $page; if ( isset( $_REQUEST['s'] ) ) {
$this->showSearchForm(); $cnt = $this->prepare_items( sanitize_text_field( wp_unslash( $_REQUEST['s'] ) ) );
parent::__construct ( array ( } else {
'singular' => __ ( 'site', 'wp-piwik' ), $cnt = $this->prepare_items();
'plural' => __ ( 'sites', 'wp-piwik' ), }
'ajax' => false $this->show_search_form();
) ); parent::__construct(
if ($cnt > 0) array(
$this->display (); 'singular' => __( 'site', 'wp-piwik' ),
else 'plural' => __( 'sites', 'wp-piwik' ),
echo '<p>' . __ ( 'No site configured yet.', 'wp-piwik' ) . '</p>'; 'ajax' => false,
)
);
if ( $cnt > 0 ) {
$this->display();
} else {
echo '<p>' . esc_html__( '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 ();
$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' )) {
$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)); $current_page = $this->get_pagenum();
$blogs = \WP_Piwik\Settings::getBlogList($per_page, $current_page, $search); $per_page = 10;
if ( is_plugin_active_for_network( 'wp-piwik/wp-piwik.php' ) ) {
$search = '%' . $wpdb->esc_like( $search ) . '%';
$total_items = $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %s WHERE CONCAT(domain, path) LIKE %s AND spam = 0 AND deleted = 0', $wpdb->blogs, $search ) );
$blogs = \WP_Piwik\Settings::get_blog_list( $per_page, $current_page, $search );
foreach ( $blogs as $blog ) { foreach ( $blogs as $blog ) {
$blogDetails = get_blog_details ( $blog['blog_id'], true ); $blog_details = get_blog_details( $blog['blog_id'], true );
$this->data [] = array ( $this->data [] = array(
'name' => $blogDetails->blogname, 'name' => $blog_details->blogname,
'id' => $blogDetails->blog_id, 'id' => $blog_details->blog_id,
'siteurl' => $blogDetails->siteurl, 'siteurl' => $blog_details->siteurl,
'piwikid' => $this->wpPiwik->getPiwikSiteId ( $blogDetails->blog_id ) 'piwikid' => $this->wp_piwik->get_piwik_site_id( $blog_details->blog_id ),
); );
} }
} else { } else {
$blogDetails = get_bloginfo (); $blog_details = 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->wp_piwik->get_piwik_site_id(),
); );
$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'] ) || 'n/a' === $dataset['piwikid'] ) {
$this->data [$key] ['piwikid'] = __ ( 'Site not created yet.', 'wp-piwik' ); $this->data [ $key ] ['piwikid'] = __( 'Site not created yet.', 'wp-piwik' );
if ($this->wpPiwik->isNetworkMode ()) }
$this->data [$key] ['name'] = '<a href="index.php?page=wp-piwik_stats&wpmu_show_stats=' . $dataset ['id'] . '">' . $dataset ['name'] . '</a>'; if ( $this->wp_piwik->is_network_mode() ) {
$this->data [ $key ] ['name'] = '<a href="index.php?page=wp-piwik_stats&wpmu_show_stats=' . esc_attr( rawurlencode( $dataset['id'] ) ) . '">' . esc_html( $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 show_search_form() {
?> $page = isset( $_REQUEST['page'] ) ? sanitize_text_field( wp_unslash( $_REQUEST['page'] ) ) : '';
<form method="post"> ?>
<input type="hidden" name="page" value="<?php echo filter_var($_REQUEST['page'], FILTER_SANITIZE_STRING) ?>" /> <form method="post">
<?php $this->search_box('Search domain and path', 'wpPiwikSiteSearch'); ?> <input type="hidden" name="page" value="<?php echo esc_attr( $page ); ?>" />
</form> <?php $this->search_box( 'Search domain and path', 'wpPiwikSiteSearch' ); ?>
<?php </form>
} <?php
}
} }

View File

@ -1,47 +1,55 @@
<?php <?php
namespace WP_Piwik\Admin; namespace WP_Piwik\Admin;
class Statistics extends \WP_Piwik\Admin { class Statistics extends \WP_Piwik\Admin {
public function show() { /**
global $screen_layout_columns; * @return void
if (empty($screen_layout_columns)) $screen_layout_columns = 2; * @phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
if (self::$settings->getGlobalOption('disable_timelimit')) set_time_limit(0); */
echo '<div id="wp-piwik-stats-general" class="wrap">'; public function show() {
echo '<h2>'.(self::$settings->getGlobalOption('plugin_display_name') == 'WP-Piwik'?'Piwik '.__('Statistics', 'wp-piwik'):self::$settings->getGlobalOption('plugin_display_name')).'</h2>'; global $screen_layout_columns;
if (self::$settings->checkNetworkActivation() && function_exists('is_super_admin') && is_super_admin()) { if ( empty( $screen_layout_columns ) ) {
$screen_layout_columns = 2;
if (isset($_GET['wpmu_show_stats'])) {
switch_to_blog((int) $_GET['wpmu_show_stats']);
} elseif ((isset($_GET['overview']) && $_GET['overview']) || (function_exists('is_network_admin') && is_network_admin())) {
new \WP_Piwik\Admin\Sitebrowser(self::$wpPiwik);
return;
}
echo '<p>'.__('Currently shown stats:').' <a href="'.get_bloginfo('url').'">'.get_bloginfo('name').'</a>.'.' <a href="?page=wp-piwik_stats&overview=1">Show site overview</a>.</p>';
}
echo '<form action="admin-post.php" method="post"><input type="hidden" name="action" value="save_wp-piwik_stats_general" /><div id="dashboard-widgets" class="metabox-holder columns-'.$screen_layout_columns.(2 <= $screen_layout_columns?' has-right-sidebar':'').'">';
wp_nonce_field('wp-piwik_stats-general');
wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false);
wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false);
$columns = array('normal', 'side', 'column3');
for ($i = 0; $i < 3; $i++) {
echo '<div id="postbox-container-'.($i+1).'" class="postbox-container">';
do_meta_boxes(self::$wpPiwik->statsPageId, $columns[$i], null);
echo '</div>';
}
echo '</div></form></div>';
echo '<script>//<![CDATA['."\n";
echo 'jQuery(document).ready(function($) {$(".if-js-closed").removeClass("if-js-closed").addClass("closed"); postboxes.add_postbox_toggles("'.self::$wpPiwik->statsPageId.'");});'."\n";
echo '//]]></script>'."\n";
if (self::$settings->checkNetworkActivation() && function_exists('is_super_admin') && is_super_admin()) {
restore_current_blog();
}
} }
if ( self::$settings->get_global_option( 'disable_timelimit' ) ) {
public function printAdminScripts() { set_time_limit( 0 );
wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true); }
wp_enqueue_script ( 'wp-piwik-chartjs', self::$wpPiwik->getPluginURL () . 'js/chartjs/chart.min.js', "3.4.1" ); echo '<div id="wp-piwik-stats-general" class="wrap">';
echo '<h2>' . esc_html( 'WP-Piwik' === self::$settings->get_global_option( 'plugin_display_name' ) ? 'Piwik ' . esc_html__( 'Statistics', 'wp-piwik' ) : self::$settings->get_global_option( 'plugin_display_name' ) ) . '</h2>';
if ( self::$settings->check_network_activation() && function_exists( 'is_super_admin' ) && is_super_admin() ) {
if ( isset( $_GET['wpmu_show_stats'] ) ) {
switch_to_blog( (int) $_GET['wpmu_show_stats'] );
} elseif ( ! empty( $_GET['overview'] ) || ( function_exists( 'is_network_admin' ) && is_network_admin() ) ) {
new \WP_Piwik\Admin\Sitebrowser( self::$wp_piwik );
return;
}
echo '<p>' . esc_html__( 'Currently shown stats:', 'wp-piwik' ) . ' <a href="' . esc_attr( get_bloginfo( 'url' ) ) . '">' . esc_html( get_bloginfo( 'name' ) ) . '</a>. <a href="?page=wp-piwik_stats&overview=1">Show site overview</a>.</p>';
}
echo '<form action="admin-post.php" method="post"><input type="hidden" name="action" value="save_wp-piwik_stats_general" /><div id="dashboard-widgets" class="metabox-holder columns-' . esc_attr( $screen_layout_columns ) . esc_attr( 2 <= $screen_layout_columns ? ' has-right-sidebar' : '' ) . '">';
wp_nonce_field( 'wp-piwik_stats-general' );
wp_nonce_field( 'closedpostboxes', 'closedpostboxesnonce', false );
wp_nonce_field( 'meta-box-order', 'meta-box-order-nonce', false );
$columns = array( 'normal', 'side', 'column3' );
for ( $i = 0; $i < 3; $i++ ) {
// @phpstan-ignore-next-line
echo '<div id="postbox-container-' . esc_attr( $i + 1 ) . '" class="postbox-container">';
do_meta_boxes( self::$wp_piwik->stats_page_id, $columns[ $i ], null );
echo '</div>';
}
echo '</div></form></div>';
echo '<script>//<![CDATA[' . "\n";
echo 'jQuery(document).ready(function($) {$(".if-js-closed").removeClass("if-js-closed").addClass("closed"); postboxes.add_postbox_toggles(' . wp_json_encode( self::$wp_piwik->stats_page_id ) . ');});' . "\n";
echo '//]]></script>' . "\n";
if ( self::$settings->check_network_activation() && function_exists( 'is_super_admin' ) && is_super_admin() ) {
restore_current_blog();
} }
} }
public function print_admin_scripts() {
$version = self::$wp_piwik->get_plugin_version();
wp_enqueue_script( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'js/wp-piwik.js', array(), $version, true );
wp_enqueue_script( 'wp-piwik-chartjs', self::$wp_piwik->get_plugin_url() . 'js/chartjs/chart.min.js', array(), $version, false );
}
}

View File

@ -0,0 +1,175 @@
<?php
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
* @package matomo
*/
namespace WP_Piwik;
if ( ! defined( 'ABSPATH' ) ) {
exit; // if accessed directly
}
if ( ! class_exists( '\WP_Piwik\MatomoTracker' ) ) {
require_once __DIR__ . '/../../libs/matomo-php-tracker/MatomoTracker.php';
}
/**
* @phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
* @phpcs:disable WordPress.NamingConventions.ValidVariableName.VariableNotSnakeCase
* @phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod.Found
*/
class AjaxTracker extends \WP_Piwik\MatomoTracker {
private $has_cookie = false;
private $logger;
public function __construct( Settings $settings, Logger $logger ) {
$this->logger = $logger;
$idsite = $settings->get_option( 'site_id' );
if ( ! $idsite ) {
return;
}
$api_endpoint = rtrim( $settings->get_matomo_url(), '/' ) . '/matomo.php';
parent::__construct( (int) $idsite, $api_endpoint );
$this->ip = false;
if ( ! $settings->get_global_option( 'disable_cookies' ) ) {
$cookie_domain = $this->get_tracking_cookie_domain( $settings );
$this->enableCookies( $cookie_domain );
} else {
$this->disableCookieSupport();
}
if ( $this->loadVisitorIdCookie() ) {
if ( ! empty( $this->cookieVisitorId ) ) {
$this->has_cookie = true;
$this->set_visitor_id_safe( $this->cookieVisitorId );
}
}
}
public function set_visitor_id_safe( $visitor_id ) {
try {
$this->setVisitorId( $visitor_id );
} catch ( \Exception $ex ) {
// do not fatal if the visitor ID is invalid for some reason
if ( ! $this->is_invalid_visitor_id_error( $ex ) ) {
throw $ex;
}
}
}
protected function setCookie( $cookieName, $cookieValue, $cookieTTL ) {
if ( ! $this->has_cookie ) {
// we only set / overwrite cookies if it is a visitor that has eg no JS enabled or ad blocker enabled etc.
// this way we will track all cart updates and orders into the same visitor on following requests.
// If we recognized the visitor before via cookie we want in our case to make sure to not overwrite
// any cookie
return parent::setCookie( $cookieName, $cookieValue, $cookieTTL );
}
return $this;
}
protected function sendRequest( string $url, string $method = 'GET', $data = null, bool $force = false ): string {
if ( ! $this->idSite ) {
$this->logger->log( 'ecommerce tracking could not find idSite, cannot send request' );
return ''; // not installed or synced yet
}
if ( $this->is_prerender() ) {
// do not track if for some reason we are prerendering
return '';
}
$args = array(
'method' => $method,
'headers' => array(
'User-Agent' => $this->userAgent,
),
'blocking' => false,
);
if ( ! empty( $data ) ) {
$args['body'] = $data;
}
$url = $url . '&bots=1';
try {
$response = $this->wp_remote_request( $url, $args );
} catch ( \Exception $ex ) {
$this->logger->log( 'ajax_tracker: ' . $ex->getMessage() );
return '';
}
if ( is_wp_error( $response ) ) {
$this->logger->log( 'ajax_tracker: ' . new \Exception( $response->get_error_message() ) );
return '';
}
return $response['body'];
}
private function is_invalid_visitor_id_error( \Exception $ex ) {
return strpos( $ex->getMessage(), 'setVisitorId() expects' ) === 0;
}
/**
* See https://developer.chrome.com/docs/web-platform/prerender-pages
*
* @return bool
*/
private function is_prerender() {
// phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$purpose = strtolower( isset( $_SERVER['HTTP_SEC_PURPOSE'] ) ? wp_unslash( $_SERVER['HTTP_SEC_PURPOSE'] ) : '' );
return strpos( $purpose, 'prefetch' ) !== false
|| strpos( $purpose, 'prerender' ) !== false;
}
/**
* for tests to override
*
* @param string $url
* @param array $args
* @return array|\WP_Error
*/
protected function wp_remote_request( $url, $args ) {
return wp_remote_request( $url, $args );
}
/**
* In Connect Matomo we want to rely entirely on JavaScript tracker
* for creating cookies.
*
* @return self
*/
protected function setFirstPartyCookies() {
// disabled
return $this;
}
public static function getCurrentUrl(): string {
return parent::getCurrentUrl();
}
public function get_tracking_cookie_domain( Settings $settings ) {
if (
$settings->get_global_option( 'track_across' )
|| $settings->get_global_option( 'track_crossdomain_linking' )
) {
$host = wp_parse_url( home_url(), PHP_URL_HOST );
if ( ! empty( $host ) ) {
return '*.' . $host;
}
}
return '';
}
}

View File

@ -1,47 +1,57 @@
<?php <?php
namespace WP_Piwik; namespace WP_Piwik;
abstract class Logger { abstract class Logger {
private $loggerName = 'unnamed'; private $logger_name = 'unnamed';
private $loggerContent = array(); private $start_microtime = null;
private $startMicrotime = null;
abstract function loggerOutput($loggerTime, $loggerMessage); abstract public function logger_output( $logger_time, $logger_message );
public function __construct($loggerName) {
$this->setName($loggerName);
$this->setStartMicrotime(microtime(true));
$this->log('Logging started -------------------------------');
}
public function __destruct() {
$this->log('Logging finished ------------------------------');
}
public function log($loggerMessage) {
$this->loggerOutput($this->getElapsedMicrotime(), $loggerMessage);
}
private function setName($loggerName) {
$this->loggerName = $loggerName;
}
public function getName() {
return $this->loggerName;
}
private function setStartMicrotime($startMicrotime) {
$this->startMicrotime = $startMicrotime;
}
public function getStartMicrotime() {
return $this->startMicrotime;
}
public function getElapsedMicrotime() {
return microtime(true) - $this->getStartMicrotime();
}
public function __construct( $logger_name ) {
$this->set_name( $logger_name );
$this->set_start_microtime( microtime( true ) );
$this->log( 'Logging started -------------------------------' );
} }
public static function make_logger() {
$logger = defined( 'WP_PIWIK_ACTIVATE_LOGGER' ) ? WP_PIWIK_ACTIVATE_LOGGER : 0;
switch ( $logger ) {
case 1:
return new \WP_Piwik\Logger\Screen( __CLASS__ );
case 2:
return new \WP_Piwik\Logger\File( __CLASS__ );
default:
return new \WP_Piwik\Logger\Dummy( __CLASS__ );
}
}
public function __destruct() {
$this->log( 'Logging finished ------------------------------' );
}
public function log( $logger_message ) {
$this->logger_output( $this->get_elapsed_microtime(), $logger_message );
}
private function set_name( $logger_name ) {
$this->logger_name = $logger_name;
}
public function get_name() {
return $this->logger_name;
}
private function set_start_microtime( $start_microtime ) {
$this->start_microtime = $start_microtime;
}
public function get_start_microtime() {
return $this->start_microtime;
}
public function get_elapsed_microtime() {
return microtime( true ) - $this->get_start_microtime();
}
}

View File

@ -1,9 +1,10 @@
<?php <?php
namespace WP_Piwik\Logger; namespace WP_Piwik\Logger;
class Dummy extends \WP_Piwik\Logger { class Dummy extends \WP_Piwik\Logger {
public function loggerOutput($loggerTime, $loggerMessage) {} public function logger_output( $logger_time, $logger_message ) {
// empty
} }
}

View File

@ -1,48 +1,55 @@
<?php <?php
namespace WP_Piwik\Logger; namespace WP_Piwik\Logger;
class File extends \WP_Piwik\Logger { /**
* @phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_fopen
* @phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_fclose
* @phpcs:disable WordPress.WP.AlternativeFunctions.file_system_operations_fwrite
*/
class File extends \WP_Piwik\Logger {
private $loggerFile = null; private $logger_file = null;
private function encodeFilename($fileName) { private function encode_filename( $file_name ) {
$fileName = str_replace (' ', '_', $fileName); $file_name = str_replace( ' ', '_', $file_name );
preg_replace('/[^0-9^a-z^_^.]/', '', $fileName); preg_replace( '/[^0-9^a-z^_^.]/', '', $file_name );
return $fileName; return $file_name;
}
private function set_filename() {
$this->logger_file = WP_PIWIK_PATH . 'logs' . DIRECTORY_SEPARATOR .
gmdate( 'Ymd' ) . '_' . $this->encode_filename( $this->get_name() ) . '.log';
}
private function get_filename() {
return $this->logger_file;
}
private function open_file() {
if ( ! $this->logger_file ) {
$this->set_filename();
} }
return fopen( $this->get_filename(), 'a' );
}
private function setFilename() { private function close_file( $file_handle ) {
$this->loggerFile = WP_PIWIK_PATH.'logs'.DIRECTORY_SEPARATOR. fclose( $file_handle );
date('Ymd').'_'.$this->encodeFilename($this->getName()).'.log'; }
}
private function getFilename() { private function write_file( $file_handle, $file_content ) {
return $this->loggerFile; fwrite( $file_handle, $file_content . "\n" );
} }
private function openFile() { private function format_microtime( $logger_time ) {
if (!$this->loggerFile) return sprintf( '[%6s sec]', number_format( $logger_time, 3 ) );
$this->setFilename(); }
return fopen($this->getFilename(), 'a');
}
private function closeFile($fileHandle) { public function logger_output( $logger_time, $logger_message ) {
fclose($fileHandle); $file_handle = $this->open_file();
if ( $file_handle ) {
$this->write_file( $file_handle, $this->format_microtime( $logger_time ) . ' ' . $logger_message );
$this->close_file( $file_handle );
} }
}
private function writeFile($fileHandle, $fileContent) { }
fwrite($fileHandle, $fileContent."\n");
}
private function formatMicrotime($loggerTime) {
return sprintf('[%6s sec]',number_format($loggerTime,3));
}
public function loggerOutput($loggerTime, $loggerMessage) {
if ($fileHandle = $this->openFile()) {
$this->writeFile($fileHandle, $this->formatMicrotime($loggerTime).' '.$loggerMessage);
$this->closeFile($fileHandle);
}
}
}

View File

@ -1,27 +1,27 @@
<?php <?php
namespace WP_Piwik\Logger; namespace WP_Piwik\Logger;
class Screen extends \WP_Piwik\Logger { class Screen extends \WP_Piwik\Logger {
private $logs = array(); private $logs = array();
private function formatMicrotime($loggerTime) { private function format_microtime( $logger_time ) {
return sprintf('[%6s sec]',number_format($loggerTime,3)); return sprintf( '[%6s sec]', number_format( $logger_time, 3 ) );
} }
public function __construct($loggerName) { public function __construct( $logger_name ) {
add_action(is_admin()?'admin_footer':'wp_footer', array($this, 'echoResults')); add_action( is_admin() ? 'admin_footer' : 'wp_footer', array( $this, 'echo_results' ) );
parent::__construct($loggerName); parent::__construct( $logger_name );
} }
public function loggerOutput($loggerTime, $loggerMessage) { public function logger_output( $logger_time, $logger_message ) {
$this->logs[] = $this->formatMicrotime($loggerTime).' '.$loggerMessage; $this->logs[] = $this->format_microtime( $logger_time ) . ' ' . $logger_message;
} }
public function echoResults() { public function echo_results() {
echo '<pre>'; echo '<pre>';
print_r($this->logs); print_r( $this->logs );
echo '</pre>'; echo '</pre>';
} }
} }

View File

@ -1,95 +1,132 @@
<?php <?php
namespace WP_Piwik; namespace WP_Piwik;
abstract class Request { abstract class Request {
protected static $wpPiwik, $settings, $debug, $lastError = '', $requests = array(), $results = array(), $isCacheable = array(), $piwikVersion; /**
* @var \WP_Piwik
*/
protected static $wp_piwik;
public function __construct($wpPiwik, $settings) { /**
self::$wpPiwik = $wpPiwik; * @var Settings
self::$settings = $settings; */
self::register('API.getPiwikVersion', array()); protected static $settings;
} protected static $debug;
protected static $last_error = '';
public function reset() { protected static $requests = array();
self::$debug = null; protected static $results = array();
self::$requests = array(); protected static $is_cacheable = array();
self::$results = array(); protected static $piwik_version;
self::$isCacheable = array();
self::$piwikVersion = null;
}
public static function register($method, $parameter) {
if ($method == 'API.getPiwikVersion')
$id = 'global.getPiwikVersion';
else
$id = 'method='.$method.self::parameterToString($parameter);
if (
in_array( $method, array( 'API.getPiwikVersion', 'SitesManager.getJavascriptTag', 'SitesManager.getSitesWithAtLeastViewAccess', 'SitesManager.getSitesIdFromSiteUrl', 'SitesManager.addSite', 'SitesManager.updateSite', 'SitesManager.getSitesWithAtLeastViewAccess' ) ) ||
!isset( $parameter['date'] ) ||
!isset( $parameter['period'] ) ||
substr($parameter['date'], 0, 4) == 'last' ||
$parameter['date'] == 'today' ||
( $parameter['period'] == 'day' && $parameter['date'] == date('Ymd') ) ||
( $parameter['period'] == 'month' && $parameter['date'] == date('Ym') ) ||
( $parameter['period'] == 'week' && $parameter['date'] == date( 'Ymd', strtotime( "last Monday" ) ) )
) self::$isCacheable[$id] = false;
else self::$isCacheable[$id] = $method.'-'.serialize($parameter);
if (!isset(self::$requests[$id]))
self::$requests[$id] = array('method' => $method, 'parameter' => $parameter);
return $id;
}
private static function parameterToString($parameter) {
$return = '';
if (is_array($parameter))
foreach ($parameter as $key => $value)
$return .= '&'.$key.'='.$value;
return $return;
}
public function perform($id) {
if ( self::$settings->getGlobalOption('cache') && false !== ( $cached = get_transient( 'wp-piwik_c_'.md5(self::$isCacheable[$id] ) ) ) ) {
if (!empty ( $cached ) && !(! empty ( $cached['result'] ) && $cached['result'] == 'error') ) {
self::$wpPiwik->log("Deliver cached data: ".$id);
return $cached;
}
}
self::$wpPiwik->log("Perform request: ".$id);
if (!isset(self::$requests[$id]))
return array('result' => 'error', 'message' => 'Request '.$id.' was not registered.');
elseif (!isset(self::$results[$id])) {
$this->request($id);
}
if ( isset ( self::$results[$id] ) ) {
if ( self::$settings->getGlobalOption('cache') && self::$isCacheable[$id] ) {
set_transient( 'wp-piwik_c_'.md5(self::$isCacheable[$id]) , self::$results[$id], WEEK_IN_SECONDS );
}
return self::$results[$id];
} else return false;
}
public function getDebug($id) {
return isset( self::$debug[$id] )? self::$debug[$id] : false;
}
protected function buildURL($config, $urlDecode = false) {
$url = 'method='.($config['method']).'&idSite='.self::$settings->getOption('site_id');
foreach ($config['parameter'] as $key => $value)
$url .= '&'.$key.'='.($urlDecode?urldecode($value):$value);
return $url;
}
protected function unserialize($str) {
self::$wpPiwik->log("Result string: ".$str);
return ($str == json_decode(false, true) || @json_decode($str, true) !== false)?json_decode($str, true):array();
}
public static function getLastError() {
return self::$lastError;
}
abstract protected function request($id);
public function __construct( $wp_piwik, $settings ) {
self::$wp_piwik = $wp_piwik;
self::$settings = $settings;
self::register( 'API.getPiwikVersion', array() );
} }
public function reset() {
self::$debug = null;
self::$requests = array();
self::$results = array();
self::$is_cacheable = array();
self::$piwik_version = null;
}
public static function register( $method, $parameter ) {
if ( 'API.getPiwikVersion' === $method ) {
$id = 'global.getPiwikVersion';
} else {
$id = 'method=' . $method . self::parameter_to_string( $parameter );
}
if (
in_array( $method, array( 'API.getPiwikVersion', 'SitesManager.getJavascriptTag', 'SitesManager.getSitesWithAtLeastViewAccess', 'SitesManager.getSitesIdFromSiteUrl', 'SitesManager.addSite', 'SitesManager.updateSite', 'SitesManager.getSitesWithAtLeastViewAccess' ), true ) ||
! isset( $parameter['date'] ) ||
! isset( $parameter['period'] ) ||
'last' === substr( $parameter['date'], 0, 4 ) ||
'today' === $parameter['date'] ||
( 'day' === $parameter['period'] && gmdate( 'Ymd' ) === $parameter['date'] ) ||
( 'month' === $parameter['period'] && gmdate( 'Ym' ) === $parameter['date'] ) ||
( 'week' === $parameter['period'] && gmdate( 'Ymd', strtotime( 'last Monday' ) ) === $parameter['date'] )
) {
self::$is_cacheable[ $id ] = false;
} else {
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.serialize_serialize
self::$is_cacheable[ $id ] = $method . '-' . serialize( $parameter );
}
if ( ! isset( self::$requests[ $id ] ) ) {
self::$requests[ $id ] = array(
'method' => $method,
'parameter' => $parameter,
);
}
return $id;
}
private static function parameter_to_string( $parameter ) {
$return = '';
if ( is_array( $parameter ) ) {
foreach ( $parameter as $key => $value ) {
$return .= '&' . $key . '=' . $value;
}
}
return $return;
}
public function perform( $id ) {
if ( self::$settings->get_global_option( 'cache' ) ) {
$cached = get_transient( 'wp-piwik_c_' . md5( self::$is_cacheable[ $id ] ) );
if ( ! empty( $cached ) && ! ( ! empty( $cached['result'] ) && 'error' === $cached['result'] ) ) {
self::$wp_piwik->log( 'Deliver cached data: ' . $id );
return $cached;
}
}
self::$wp_piwik->log( 'Perform request: ' . $id );
if ( ! isset( self::$requests[ $id ] ) ) {
return array(
'result' => 'error',
'message' => 'Request ' . $id . ' was not registered.',
);
} elseif ( ! isset( self::$results[ $id ] ) ) {
$this->request( $id );
}
if ( isset( self::$results[ $id ] ) ) {
if ( self::$settings->get_global_option( 'cache' ) && self::$is_cacheable[ $id ] ) {
set_transient( 'wp-piwik_c_' . md5( self::$is_cacheable[ $id ] ), self::$results[ $id ], WEEK_IN_SECONDS );
}
return self::$results[ $id ];
} else {
return false;
}
}
public function get_debug( $id ) {
return isset( self::$debug[ $id ] ) ? self::$debug[ $id ] : false;
}
protected function build_url( $config ) {
return http_build_query( $this->get_url_params( $config ), '', '&' );
}
protected function get_url_params( $config ) {
$params = [
'method' => $config['method'],
'idSite' => self::$settings->get_option( 'site_id' ),
];
$params = array_merge( $params, $config['parameter'] );
return $params;
}
protected function unserialize( $str ) {
self::$wp_piwik->log( 'Result string: ' . $str );
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
return ( json_decode( '', true ) === $str || false !== @json_decode( $str, true ) ) ? json_decode( $str, true ) : array();
}
public static function get_last_error() {
return self::$last_error;
}
abstract protected function request( $id );
}

View File

@ -1,64 +1,94 @@
<?php <?php
namespace WP_Piwik\Request; namespace WP_Piwik\Request;
class Php extends \WP_Piwik\Request { class Php extends \WP_Piwik\Request {
private static $piwikEnvironment = false; /**
* @var mixed
*/
private static $piwik_environment = false;
protected function request($id) { protected function request( $id ) {
$count = 0; $count = 0;
$url = self::$settings->getGlobalOption('piwik_url'); $url = self::$settings->get_global_option( 'piwik_url' );
foreach (self::$requests as $requestID => $config) { foreach ( self::$requests as $request_id => $config ) {
if (!isset(self::$results[$requestID])) { if ( ! isset( self::$results[ $request_id ] ) ) {
if (self::$settings->getGlobalOption('filter_limit') != "" && self::$settings->getGlobalOption('filter_limit') == (int) self::$settings->getGlobalOption('filter_limit')) if ( '' !== self::$settings->get_global_option( 'filter_limit' ) && is_numeric( self::$settings->get_global_option( 'filter_limit' ) ) ) {
$config['parameter']['filter_limit'] = self::$settings->getGlobalOption('filter_limit'); $config['parameter']['filter_limit'] = self::$settings->get_global_option( 'filter_limit' );
$params = 'module=API&format=json&'.$this->buildURL($config, true);
$map[$count] = $requestID;
$result = $this->call($id, $url, $params);
self::$results[$map[$count]] = $result;
$count++;
} }
$params = $this->get_url_params( $config );
$params['module'] = 'API';
$params['format'] = 'json';
$map[ $count ] = $request_id;
$result = $this->call( $id, $url, $params );
self::$results[ $map[ $count ] ] = $result;
++$count;
} }
} }
private function call($id, $url, $params) {
if (!defined('PIWIK_INCLUDE_PATH'))
return false;
if (PIWIK_INCLUDE_PATH === FALSE)
return array('result' => 'error', 'message' => __('Could not resolve','wp-piwik').' &quot;'.htmlentities(self::$settings->getGlobalOption('piwik_path')).'&quot;: '.__('realpath() returns false','wp-piwik').'.');
if (file_exists(PIWIK_INCLUDE_PATH . "/index.php"))
require_once PIWIK_INCLUDE_PATH . "/index.php";
if (file_exists(PIWIK_INCLUDE_PATH . "/core/API/Request.php"))
require_once PIWIK_INCLUDE_PATH . "/core/API/Request.php";
if (class_exists('\Piwik\Application\Environment') && !self::$piwikEnvironment) {
// Piwik 2.14.* compatibility fix
self::$piwikEnvironment = new \Piwik\Application\Environment(null);
self::$piwikEnvironment->init();
}
if (class_exists('Piwik\FrontController'))
\Piwik\FrontController::getInstance()->init();
else return array('result' => 'error', 'message' => __('Class Piwik\FrontController does not exists.','wp-piwik'));
if (class_exists('Piwik\API\Request'))
$request = new \Piwik\API\Request($params.'&token_auth='.self::$settings->getGlobalOption('piwik_token'));
else return array('result' => 'error', 'message' => __('Class Piwik\API\Request does not exists.','wp-piwik'));
if (isset($request))
$result = $request->process();
else $result = null;
if (!headers_sent())
header("Content-Type: text/html", true);
$result = $this->unserialize($result);
if ($GLOBALS ['wp-piwik_debug'])
self::$debug[$id] = array ( $params.'&token_auth=...' );
return $result;
}
public function reset() {
if (class_exists('\Piwik\Application\Environment') && !self::$piwikEnvironment) {
self::$piwikEnvironment->destroy();
}
if (class_exists('Piwik\FrontController'))
\Piwik\FrontController::unsetInstance();
parent::reset();
}
} }
private function call( $id, $url, $params ) {
if ( ! defined( 'PIWIK_INCLUDE_PATH' ) ) {
return false;
}
if ( PIWIK_INCLUDE_PATH === false ) {
return array(
'result' => 'error',
'message' => __( 'Could not resolve', 'wp-piwik' ) . ' &quot;' . htmlentities( self::$settings->get_global_option( 'piwik_path' ) ) . '&quot;: ' . __( 'realpath() returns false', 'wp-piwik' ) . '.',
);
}
if ( file_exists( PIWIK_INCLUDE_PATH . '/index.php' ) ) {
require_once PIWIK_INCLUDE_PATH . '/index.php';
}
if ( file_exists( PIWIK_INCLUDE_PATH . '/core/API/Request.php' ) ) {
require_once PIWIK_INCLUDE_PATH . '/core/API/Request.php';
}
if ( class_exists( '\Piwik\Application\Environment' ) && ! self::$piwik_environment ) {
// Piwik 2.14.* compatibility fix
self::$piwik_environment = new \Piwik\Application\Environment( null );
self::$piwik_environment->init();
}
if ( class_exists( 'Piwik\FrontController' ) ) {
\Piwik\FrontController::getInstance()->init();
} else {
return array(
'result' => 'error',
'message' => __( 'Class Piwik\FrontController does not exists.', 'wp-piwik' ),
);
}
if ( class_exists( 'Piwik\API\Request' ) ) {
$params['token_auth'] = self::$settings->get_global_option( 'piwik_token' );
$request = new \Piwik\API\Request( $params );
} else {
return array(
'result' => 'error',
'message' => __( 'Class Piwik\API\Request does not exists.', 'wp-piwik' ),
);
}
$result = $request->process();
if ( ! headers_sent() ) {
header( 'Content-Type: text/html', true );
}
$result = $this->unserialize( $result );
if ( $GLOBALS ['wp-piwik_debug'] ) {
self::$debug[ $id ] = array( $params . '&token_auth=...' );
}
return $result;
}
public function reset() {
if (
class_exists( '\Piwik\Application\Environment' )
&& self::$piwik_environment instanceof \Piwik\Application\Environment
) {
self::$piwik_environment->destroy();
}
if ( class_exists( 'Piwik\FrontController' ) ) {
\Piwik\FrontController::unsetInstance();
}
parent::reset();
}
}

View File

@ -1,81 +1,124 @@
<?php <?php
namespace WP_Piwik\Request; namespace WP_Piwik\Request;
class Rest extends \WP_Piwik\Request { /**
* TODO: switch to wp_remote_get
* phpcs:disable WordPress.WP.AlternativeFunctions.curl_curl_close
* phpcs:disable WordPress.WP.AlternativeFunctions.curl_curl_getinfo
* phpcs:disable WordPress.WP.AlternativeFunctions.curl_curl_error
* phpcs:disable WordPress.WP.AlternativeFunctions.curl_curl_init
* phpcs:disable WordPress.WP.AlternativeFunctions.curl_curl_setopt
* phpcs:disable WordPress.WP.AlternativeFunctions.curl_curl_exec
* phpcs:disable WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
*/
class Rest extends \WP_Piwik\Request {
protected function request($id) { protected function request( $id ) {
$count = 0; $count = 0;
if (self::$settings->getGlobalOption('piwik_mode') == 'http') $url = self::$settings->get_matomo_url();
$url = self::$settings->getGlobalOption('piwik_url'); $params = 'module=API&method=API.getBulkRequest&format=json';
else if (self::$settings->getGlobalOption('piwik_mode') == 'cloud')
$url = 'https://'.self::$settings->getGlobalOption('piwik_user').'.innocraft.cloud/'; $filter_limit = self::$settings->get_global_option( 'filter_limit' );
else $url = 'https://'.self::$settings->getGlobalOption('matomo_user').'.matomo.cloud/'; if (
$params = 'module=API&method=API.getBulkRequest&format=json'; $filter_limit > 0
if (self::$settings->getGlobalOption('filter_limit') != "" && self::$settings->getGlobalOption('filter_limit') == (int) self::$settings->getGlobalOption('filter_limit')) && is_numeric( self::$settings->get_global_option( 'filter_limit' ) )
$params .= '&filter_limit='.self::$settings->getGlobalOption('filter_limit'); ) {
foreach (self::$requests as $requestID => $config) { $params .= '&filter_limit=' . self::$settings->get_global_option( 'filter_limit' );
if (!isset(self::$results[$requestID])) { }
$params .= '&urls['.$count.']='.urlencode($this->buildURL($config)); foreach ( self::$requests as $request_id => $config ) {
$map[$count] = $requestID; if ( ! isset( self::$results[ $request_id ] ) ) {
$count++; $params .= '&urls[' . $count . ']=' . rawurlencode( $this->build_url( $config ) );
$map[ $count ] = $request_id;
++$count;
}
}
$use_curl = (
function_exists( 'curl_init' )
&& ini_get( 'allow_url_fopen' )
&& 'curl' === self::$settings->get_global_option( 'http_connection' )
) || (
function_exists( 'curl_init' )
&& ! ini_get( 'allow_url_fopen' )
);
$results = $use_curl ? $this->curl( $id, $url, $params ) : $this->fopen( $id, $url, $params );
if ( is_array( $results ) ) {
foreach ( $results as $num => $result ) {
if ( isset( $map[ $num ] ) ) {
self::$results[ $map[ $num ] ] = $result;
} }
} }
$results = ((function_exists('curl_init') && ini_get('allow_url_fopen') && self::$settings->getGlobalOption('http_connection') == 'curl') || (function_exists('curl_init') && !ini_get('allow_url_fopen')))?$this->curl($id, $url, $params):$this->fopen($id, $url, $params);
if (is_array($results))
foreach ($results as $num => $result)
if (isset($map[$num]))
self::$results[$map[$num]] = $result;
}
private function curl($id, $url, $params) {
if (self::$settings->getGlobalOption('http_method')=='post') {
$c = curl_init($url);
curl_setopt($c, CURLOPT_POST, 1);
curl_setopt($c, CURLOPT_POSTFIELDS, $params.'&token_auth='.self::$settings->getGlobalOption('piwik_token'));
} else $c = curl_init($url.'?'.$params.'&token_auth='.self::$settings->getGlobalOption('piwik_token'));
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, !self::$settings->getGlobalOption('disable_ssl_verify'));
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, !self::$settings->getGlobalOption('disable_ssl_verify_host')?2:0);
curl_setopt($c, CURLOPT_USERAGENT, self::$settings->getGlobalOption('piwik_useragent')=='php'?ini_get('user_agent'):self::$settings->getGlobalOption('piwik_useragent_string'));
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_HEADER, $GLOBALS ['wp-piwik_debug'] );
curl_setopt($c, CURLOPT_TIMEOUT, self::$settings->getGlobalOption('connection_timeout'));
$httpProxyClass = new \WP_HTTP_Proxy();
if ($httpProxyClass->is_enabled() && $httpProxyClass->send_through_proxy($url)) {
curl_setopt($c, CURLOPT_PROXY, $httpProxyClass->host());
curl_setopt($c, CURLOPT_PROXYPORT, $httpProxyClass->port());
if ($httpProxyClass->use_authentication())
curl_setopt($c, CURLOPT_PROXYUSERPWD, $httpProxyClass->username().':'.$httpProxyClass->password());
}
$result = curl_exec($c);
self::$lastError = curl_error($c);
if ($GLOBALS ['wp-piwik_debug']) {
$header_size = curl_getinfo($c, CURLINFO_HEADER_SIZE);
$header = substr($result, 0, $header_size);
$body = substr($result, $header_size);
$result = $this->unserialize($body);
self::$debug[$id] = array ( $header, $url.'?'.$params.'&token_auth=...' );
} else $result = $this->unserialize($result);
curl_close($c);
return $result;
}
private function fopen($id, $url, $params) {
$contextDefinition = array('http'=>array('timeout' => self::$settings->getGlobalOption('connection_timeout'), 'header' => "Content-type: application/x-www-form-urlencoded\r\n") );
$contextDefinition['ssl'] = array();
if (self::$settings->getGlobalOption('disable_ssl_verify'))
$contextDefinition['ssl'] = array('allow_self_signed' => true, 'verify_peer' => false );
if (self::$settings->getGlobalOption('disable_ssl_verify_host'))
$contextDefinition['ssl']['verify_peer_name'] = false;
if (self::$settings->getGlobalOption('http_method')=='post') {
$fullUrl = $url;
$contextDefinition['http']['method'] = 'POST';
$contextDefinition['http']['content'] = $params.'&token_auth='.self::$settings->getGlobalOption('piwik_token');
} else $fullUrl = $url.'?'.$params.'&token_auth='.self::$settings->getGlobalOption('piwik_token');
$context = stream_context_create($contextDefinition);
$result = $this->unserialize(@file_get_contents($fullUrl, false, $context));
if ($GLOBALS ['wp-piwik_debug'])
self::$debug[$id] = array ( get_headers($fullUrl, 1), $url.'?'.$params.'&token_auth=...' );
return $result;
} }
} }
private function curl( $id, $url, $params ) {
if ( 'post' === self::$settings->get_global_option( 'http_method' ) ) {
$c = curl_init( $url );
curl_setopt( $c, CURLOPT_POST, 1 );
curl_setopt( $c, CURLOPT_POSTFIELDS, $params . '&token_auth=' . self::$settings->get_global_option( 'piwik_token' ) );
} else {
$c = curl_init( $url . '?' . $params . '&token_auth=' . self::$settings->get_global_option( 'piwik_token' ) );
}
curl_setopt( $c, CURLOPT_SSL_VERIFYPEER, ! self::$settings->get_global_option( 'disable_ssl_verify' ) );
curl_setopt( $c, CURLOPT_SSL_VERIFYHOST, ! self::$settings->get_global_option( 'disable_ssl_verify_host' ) ? 2 : 0 );
curl_setopt( $c, CURLOPT_USERAGENT, 'php' === self::$settings->get_global_option( 'piwik_useragent' ) ? ini_get( 'user_agent' ) : self::$settings->get_global_option( 'piwik_useragent_string' ) );
curl_setopt( $c, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $c, CURLOPT_HEADER, $GLOBALS ['wp-piwik_debug'] );
curl_setopt( $c, CURLOPT_TIMEOUT, self::$settings->get_global_option( 'connection_timeout' ) );
$http_proxy_class = new \WP_HTTP_Proxy();
if ( $http_proxy_class->is_enabled() && $http_proxy_class->send_through_proxy( $url ) ) {
curl_setopt( $c, CURLOPT_PROXY, $http_proxy_class->host() );
curl_setopt( $c, CURLOPT_PROXYPORT, $http_proxy_class->port() );
if ( $http_proxy_class->use_authentication() ) {
curl_setopt( $c, CURLOPT_PROXYUSERPWD, $http_proxy_class->username() . ':' . $http_proxy_class->password() );
}
}
$result = curl_exec( $c );
self::$last_error = curl_error( $c );
if ( $GLOBALS ['wp-piwik_debug'] ) {
$header_size = curl_getinfo( $c, CURLINFO_HEADER_SIZE );
$header = substr( $result, 0, $header_size );
$body = substr( $result, $header_size );
$result = $this->unserialize( $body );
self::$debug[ $id ] = array( $header, $url . '?' . $params . '&token_auth=...' );
} else {
$result = $this->unserialize( $result );
}
curl_close( $c );
return $result;
}
private function fopen( $id, $url, $params ) {
$context_definition = array(
'http' => array(
'timeout' => self::$settings->get_global_option( 'connection_timeout' ),
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
),
);
$context_definition['ssl'] = array();
if ( self::$settings->get_global_option( 'disable_ssl_verify' ) ) {
$context_definition['ssl'] = array(
'allow_self_signed' => true,
'verify_peer' => false,
);
}
if ( self::$settings->get_global_option( 'disable_ssl_verify_host' ) ) {
$context_definition['ssl']['verify_peer_name'] = false;
}
if ( self::$settings->get_global_option( 'http_method' ) === 'post' ) {
$full_url = $url;
$context_definition['http']['method'] = 'POST';
$context_definition['http']['content'] = $params . '&token_auth=' . self::$settings->get_global_option( 'piwik_token' );
} else {
$full_url = $url . '?' . $params . '&token_auth=' . self::$settings->get_global_option( 'piwik_token' );
}
$context = stream_context_create( $context_definition );
// phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
$result = $this->unserialize( @file_get_contents( $full_url, false, $context ) );
if ( $GLOBALS ['wp-piwik_debug'] ) {
self::$debug[ $id ] = array( get_headers( $full_url, 1 ), $url . '?' . $params . '&token_auth=...' );
}
return $result;
}
}

View File

@ -7,280 +7,301 @@ namespace WP_Piwik;
* *
* @author Andr&eacute; Br&auml;kling * @author Andr&eacute; Br&auml;kling
* @package WP_Piwik * @package WP_Piwik
*
* TODO: do not disable this at some point
* @phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
* @phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
*/ */
class Settings { class Settings {
const TRACK_AI_BOTS = 'track_ai_bots';
const TRACK_AI_BOTS_USING_ESI = 'track_ai_bots_using_esi';
/** /**
* * @var \WP_Piwik variables and default settings container
* @var Environment variables and default settings container
*/ */
private static $wpPiwik, $defaultSettings; private static $wp_piwik;
private static $default_settings;
/** /**
* *
* @var Define callback functions for changed settings * @var array Define callback functions for changed settings
*/ */
private $checkSettings = array ( private $check_settings = array(
'piwik_url' => 'checkPiwikUrl', 'piwik_url' => 'check_piwik_url',
'piwik_token' => 'checkPiwikToken', 'piwik_token' => 'check_piwik_token',
'site_id' => 'requestPiwikSiteID', 'site_id' => 'request_piwik_site_id',
'tracking_code' => 'prepareTrackingCode', 'tracking_code' => 'prepare_tracking_code',
'noscript_code' => 'prepareNocscriptCode' 'noscript_code' => 'prepare_nocscript_code',
); );
/** /**
* * @var array default configuration set
* @var Register default configuration set
*/ */
private $globalSettings = array ( private $global_settings = 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' => 'Connect 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 (
'name' => '', self::TRACK_AI_BOTS => false,
'site_id' => NULL, self::TRACK_AI_BOTS_USING_ESI => false,
'noscript_code' => '', );
'tracking_code' => '',
'last_tracking_code_update' => 0, private $settings = array(
'dashboard_revision' => 0 'name' => '',
), $settingsChanged = false; 'site_id' => null,
'noscript_code' => '',
'tracking_code' => '',
'last_tracking_code_update' => 0,
'dashboard_revision' => 0,
);
private $settings_changed = false;
/** /**
* Constructor class to prepare settings manager * Constructor class to prepare settings manager
* *
* @param WP_Piwik $wpPiwik * @param \WP_Piwik $wp_piwik
* active WP-Piwik instance * active WP-Piwik instance
*/ */
public function __construct($wpPiwik) { public function __construct( $wp_piwik ) {
self::$wpPiwik = $wpPiwik; self::$wp_piwik = $wp_piwik;
self::$wpPiwik->log ( 'Store default settings' ); self::$wp_piwik->log( 'Store default settings' );
self::$defaultSettings = array ( self::$default_settings = array(
'globalSettings' => $this->globalSettings, 'globalSettings' => $this->global_settings,
'settings' => $this->settings 'settings' => $this->settings,
); );
self::$wpPiwik->log ( 'Load settings' ); self::$wp_piwik->log( 'Load settings' );
foreach ( $this->globalSettings as $key => $default ) { foreach ( $this->global_settings as $key => $default ) {
$this->globalSettings [$key] = ($this->checkNetworkActivation () ? get_site_option ( 'wp-piwik_global-' . $key, $default ) : get_option ( 'wp-piwik_global-' . $key, $default )); $this->global_settings [ $key ] = ( $this->check_network_activation() ? get_site_option( 'wp-piwik_global-' . $key, $default ) : get_option( 'wp-piwik_global-' . $key, $default ) );
}
foreach ( $this->settings as $key => $default ) {
$this->settings [ $key ] = get_option( 'wp-piwik-' . $key, $default );
} }
foreach ( $this->settings as $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) { global $wp_roles;
self::$wpPiwik->log ( 'No settings changed yet' );
if ( ! $this->settings_changed ) {
self::$wp_piwik->log( 'No settings changed yet' );
return; return;
} }
self::$wpPiwik->log ( 'Save settings' ); self::$wp_piwik->log( 'Save settings' );
$this->globalSettings['plugin_display_name'] = htmlspecialchars($this->globalSettings['plugin_display_name'], ENT_QUOTES, 'utf-8'); $this->global_settings['plugin_display_name'] = htmlspecialchars( $this->global_settings['plugin_display_name'], ENT_QUOTES, 'utf-8' );
foreach ( $this->globalSettings as $key => $value ) { foreach ( $this->global_settings as $key => $value ) {
if ( $this->checkNetworkActivation() ) if ( $this->check_network_activation() ) {
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 ) {
update_option ( 'wp-piwik-' . $key, $value );
}
global $wp_roles;
if (! is_object ( $wp_roles ))
$wp_roles = new \WP_Roles ();
if (! is_object ( $wp_roles ))
die ( "STILL NO OBJECT" );
foreach ( $wp_roles->role_names as $strKey => $strName ) {
$objRole = get_role ( $strKey );
foreach ( array (
'stealth',
'read_stats'
) as $strCap ) {
$aryCaps = $this->getGlobalOption ( 'capability_' . $strCap );
if (isset ( $aryCaps [$strKey] ) && $aryCaps [$strKey])
$wp_roles->add_cap ( $strKey, 'wp-piwik_' . $strCap );
else $wp_roles->remove_cap ( $strKey, 'wp-piwik_' . $strCap );
} }
} }
$this->settingsChanged = false; foreach ( $this->settings as $key => $value ) {
update_option( 'wp-piwik-' . $key, $value );
}
foreach ( $wp_roles->role_names as $str_key => $str_name ) {
$obj_role = get_role( $str_key );
$caps = array( 'stealth', 'read_stats' );
foreach ( $caps as $str_cap ) {
$ary_caps = $this->get_global_option( 'capability_' . $str_cap );
if ( isset( $ary_caps [ $str_key ] ) && $ary_caps [ $str_key ] ) {
$wp_roles->add_cap( $str_key, 'wp-piwik_' . $str_cap );
} else {
$wp_roles->remove_cap( $str_key, 'wp-piwik_' . $str_cap );
}
}
}
$this->settings_changed = 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 get_not_empty_global_option( $key ) {
return isset ( $this->globalSettings [$key] ) && !empty($this->globalSettings [$key]) ? $this->globalSettings [$key] : self::$defaultSettings ['globalSettings'] [$key]; return isset( $this->global_settings [ $key ] ) && ! empty( $this->global_settings [ $key ] ) ? $this->global_settings [ $key ] : self::$default_settings ['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 mixed option value
*/ */
public function getGlobalOption($key) { public function get_global_option( $key ) {
return isset ( $this->globalSettings [$key] ) ? $this->globalSettings [$key] : self::$defaultSettings ['globalSettings'] [$key]; return isset( $this->global_settings [ $key ] ) ? $this->global_settings [ $key ] : self::$default_settings ['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 $blog_id
* blog ID (default: current blog) * blog ID (default: current blog)
* @return \WP_Piwik\Register * @return mixed
*/ */
public function getOption($key, $blogID = null) { public function get_option( $key, $blog_id = null ) {
if ($this->checkNetworkActivation () && ! empty ( $blogID )) { if ( $this->check_network_activation() && ! empty( $blog_id ) ) {
return get_blog_option ( $blogID, 'wp-piwik-'.$key ); return get_blog_option( $blog_id, 'wp-piwik-' . $key );
} }
return isset ( $this->settings [$key] ) ? $this->settings [$key] : self::$defaultSettings ['settings'] [$key]; return isset( $this->settings [ $key ] ) ? $this->settings [ $key ] : self::$default_settings ['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 mixed $value
* new option value * new option value
*/ */
public function setGlobalOption($key, $value) { public function set_global_option( $key, $value ) {
$this->settingsChanged = true; $this->settings_changed = true;
self::$wpPiwik->log ( 'Changed global option ' . $key . ': ' . (is_array ( $value ) ? serialize ( $value ) : $value) ); self::$wp_piwik->log( 'Changed global option ' . $key . ': ' . ( is_array( $value ) ? wp_json_encode( $value ) : $value ) );
$this->globalSettings [$key] = $value; $this->global_settings [ $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 $blog_id
* blog ID (default: current blog) * blog ID (default: current blog)
*/ */
public function setOption($key, $value, $blogID = null) { public function set_option( $key, $value, $blog_id = null ) {
if (empty( $blogID )) { if ( empty( $blog_id ) ) {
$blogID = get_current_blog_id(); $blog_id = get_current_blog_id();
} }
$this->settingsChanged = true; $this->settings_changed = true;
self::$wpPiwik->log ( 'Changed option ' . $key . ': ' . $value ); self::$wp_piwik->log( 'Changed option ' . $key . ': ' . $value );
if ($this->checkNetworkActivation ()) { if ( $this->check_network_activation() ) {
update_blog_option ( $blogID, 'wp-piwik-'.$key, $value ); update_blog_option( $blog_id, 'wp-piwik-' . $key, $value );
} }
if ($blogID == get_current_blog_id()) { if ( get_current_blog_id() === $blog_id ) {
$this->settings [$key] = $value; $this->settings [ $key ] = $value;
} }
} }
/** /**
* Reset settings to default * Reset settings to default
*/ */
public function resetSettings() { public function reset_settings() {
self::$wpPiwik->log ( 'Reset WP-Piwik settings' ); self::$wp_piwik->log( 'Reset WP-Piwik settings' );
global $wpdb; global $wpdb;
if ( $this->checkNetworkActivation() ) { if ( $this->check_network_activation() ) {
$aryBlogs = self::getBlogList(); $ary_blogs = self::get_blog_list();
if (is_array($aryBlogs)) if ( is_array( $ary_blogs ) ) {
foreach ($aryBlogs as $aryBlog) { foreach ( $ary_blogs as $ary_blog ) {
switch_to_blog($aryBlog['blog_id']); switch_to_blog( $ary_blog['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 get_blog_list( $limit = null, $page = null, $search = '' ) {
if ($limit && $page)
$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);
$query_limit = '';
if ( $limit && $page ) {
$query_limit = ' LIMIT ' . (int) ( ( $page - 1 ) * $limit ) . ',' . (int) $limit;
}
$like = '%' . $wpdb->esc_like( $search ) . '%';
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
return $wpdb->get_results( $wpdb->prepare( 'SELECT blog_id FROM %s WHERE CONCAT(domain, path) LIKE %s AND spam = 0 AND deleted = 0 ORDER BY blog_id' . $query_limit, $wpdb->blogs, $like ), ARRAY_A );
} }
/** /**
@ -288,48 +309,56 @@ class Settings {
* *
* @return boolean Is network activated? * @return boolean Is network activated?
*/ */
public function checkNetworkActivation() { public function check_network_activation() {
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 apply_changes( $in ) {
if (!self::$wpPiwik->isValidOptionsPost()) if ( ! self::$wp_piwik->is_valid_options_post() ) {
die("Invalid config changes."); die( 'Invalid config changes.' );
$in = $this->checkSettings ( $in ); }
self::$wpPiwik->log ( 'Apply changed settings:' ); $in = $this->check_settings( $in );
foreach ( self::$defaultSettings ['globalSettings'] as $key => $val ) self::$wp_piwik->log( 'Apply changed settings:' );
$this->setGlobalOption ( $key, isset ( $in [$key] ) ? $in [$key] : $val ); foreach ( self::$default_settings ['globalSettings'] as $key => $val ) {
foreach ( self::$defaultSettings ['settings'] as $key => $val ) $this->set_global_option( $key, isset( $in [ $key ] ) ? $in [ $key ] : $val );
$this->setOption ( $key, isset ( $in [$key] ) ? $in [$key] : $val ); }
$this->setGlobalOption ( 'last_settings_update', time () ); foreach ( self::$default_settings ['settings'] as $key => $val ) {
$this->save (); $this->set_option( $key, isset( $in [ $key ] ) ? $in [ $key ] : $val );
}
$this->set_global_option( 'last_settings_update', (string) time() );
$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 check_settings( $in ) {
foreach ( $this->checkSettings as $key => $value ) foreach ( $this->check_settings 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 ( ),
$in [$key], array(
$in $in [ $key ],
) ); $in,
)
);
}
}
return $in; return $in;
} }
@ -337,78 +366,80 @@ class Settings {
* 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
* configuration set
* @return string Piwik URL * @return string Piwik URL
* @phpstan-ignore method.unused
*/ */
private function checkPiwikUrl($value, $in) { private function check_piwik_url( $value ) {
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
* configuration set
* @return string Piwik auth token * @return string Piwik auth token
* @phpstan-ignore method.unused
*/ */
private function checkPiwikToken($value, $in) { private function check_piwik_token( $value ) {
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|int $value
* tracking code * site ID setting value
* @param array $in * @param array $in
* configuration set * configuration set
* @return int Piwik site ID * @return int Piwik site ID
* @phpstan-ignore method.unused
*/ */
private function requestPiwikSiteID($value, $in) { private function request_piwik_site_id( $value, $in ) {
if ($in ['auto_site_config'] && ! $value) if ( $in ['auto_site_config'] && ! $value ) {
return self::$wpPiwik->getPiwikSiteId(); return self::$wp_piwik->get_piwik_site_id();
return $value; }
return intval( $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
* @phpstan-ignore method.unused
*/ */
private function prepareTrackingCode($value, $in) { private function prepare_tracking_code( $value, $in ) {
if ($in ['track_mode'] == 'manually' || $in ['track_mode'] == 'disabled') { if ( 'manually' === $in['track_mode'] || 'disabled' === $in['track_mode'] ) {
$value = stripslashes ( $value ); $value = stripslashes( $value );
if ($this->checkNetworkActivation ()) if ( $this->check_network_activation() ) {
update_site_option ( 'wp-piwik-manually', $value ); update_site_option( 'wp-piwik-manually', $value );
}
return $value; return $value;
} }
/*$result = self::$wpPiwik->updateTrackingCode ();
echo '<pre>'; print_r($result); echo '</pre>'; return '';
$this->setOption ( 'noscript_code', $result ['noscript'] );*/
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
* @phpstan-ignore method.unused
*/ */
private function prepareNocscriptCode($value, $in) { private function prepare_nocscript_code( $value, $in ) {
if ($in ['track_mode'] == 'manually') if ( 'manually' === $in['track_mode'] ) {
return stripslashes ( $value ); return stripslashes( $value );
return $this->getOption ( 'noscript_code' ); }
return $this->get_option( 'noscript_code' );
} }
/** /**
@ -416,12 +447,40 @@ class Settings {
* *
* @return array WP-Piwik settings for debug output * @return array WP-Piwik settings for debug output
*/ */
public function getDebugData() { public function get_debug_data() {
$debug = array( $debug = array(
'global_settings' => $this->globalSettings, 'global_settings' => $this->global_settings,
'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;
} }
public function is_ai_bot_tracking_enabled() {
return (bool) $this->get_global_option( self::TRACK_AI_BOTS );
}
public function is_ai_bot_tracking_enabled_via_esi_includes() {
return (bool) $this->get_global_option( self::TRACK_AI_BOTS_USING_ESI );
}
public function is_track_via_esi_enabled() {
return true === (bool) $this->get_global_option( 'track_ai_bots_using_esi' );
}
public function get_matomo_url() {
if ( 'http' === $this->get_global_option( 'piwik_mode' ) ) {
return $this->get_global_option( 'piwik_url' );
}
if ( 'cloud' === $this->get_global_option( 'piwik_mode' ) ) {
return 'https://' . $this->get_global_option( 'piwik_user' ) . '.innocraft.cloud/';
}
return 'https://' . $this->get_global_option( 'matomo_user' ) . '.matomo.cloud/';
}
public function is_tracking_enabled() {
return 'disabled' !== $this->get_global_option( 'track_mode' );
}
} }

View File

@ -1,28 +1,34 @@
<?php <?php
namespace WP_Piwik; namespace WP_Piwik;
class Shortcode { class Shortcode {
private $available = array( private $available = array(
'opt-out' => 'OptOut', 'opt-out' => 'OptOut',
'post' => 'Post', 'post' => 'Post',
'overview' => 'Overview' 'overview' => 'Overview',
), $content; );
public function __construct($attributes, $wpPiwik, $settings) { private $content;
$wpPiwik->log('Check requested shortcode widget '.$attributes['module']);
if (isset($attributes['module']) && isset($this->available[$attributes['module']])) { /**
$wpPiwik->log('Add shortcode widget '.$this->available[$attributes['module']]); * @param array $attributes
$class = '\\WP_Piwik\\Widget\\'.$this->available[$attributes['module']]; * @param \WP_Piwik $wp_piwik
$widget = new $class($wpPiwik, $settings, null, null, null, $attributes, true); * @param Settings $settings
$widget->show(); */
$this->content = $widget->get(); public function __construct( $attributes, $wp_piwik, $settings ) {
} $wp_piwik->log( 'Check requested shortcode widget ' . $attributes['module'] );
if ( isset( $attributes['module'] ) && isset( $this->available[ $attributes['module'] ] ) ) {
$wp_piwik->log( 'Add shortcode widget ' . $this->available[ $attributes['module'] ] );
$class = '\\WP_Piwik\\Widget\\' . $this->available[ $attributes['module'] ];
$widget = new $class( $wp_piwik, $settings, null, null, null, $attributes, true );
$widget->show();
$this->content = $widget->get();
} }
public function get() {
return $this->content;
}
} }
public function get() {
return $this->content;
}
}

View File

@ -1,31 +1,45 @@
<?php <?php
namespace WP_Piwik; namespace WP_Piwik;
class Template { class Template {
public static $logger, $settings, $wpPiwik; /**
* @var Logger
*/
public static $logger;
public function __construct($wpPiwik, $settings) { /**
self::$settings = $settings; * @var Settings
self::$wpPiwik = $wpPiwik; */
} public static $settings;
public function output($array, $key, $default = '') { /**
if (isset($array[$key])) * @var \WP_Piwik
return $array[$key]; */
else public static $wp_piwik;
return $default;
}
public function tabRow($name, $value) { public function __construct( $wp_piwik, $settings ) {
echo '<tr><td>'.$name.'</td><td>'.$value.'</td></tr>'; self::$settings = $settings;
} self::$wp_piwik = $wp_piwik;
}
public function getRangeLast30() { public function output( $values, $key, $default_value = '' ) {
$diff = (self::$settings->getGlobalOption('default_date') == 'yesterday') ? -86400 : 0; if ( isset( $values[ $key ] ) ) {
$end = time() + $diff; return $values[ $key ];
$start = time() - 2592000 + $diff; } else {
return date('Y-m-d', $start).','.date('Y-m-d', $end); return $default_value;
} }
} }
public function tab_row( $name, $value ) {
echo '<tr><td>' . esc_html( $name ) . '</td><td>' . esc_html( $value ) . '</td></tr>';
}
public function get_range_last30() {
$diff = ( self::$settings->get_global_option( 'default_date' ) === 'yesterday' ) ? -86400 : 0;
$end = time() + $diff;
$start = time() - 2592000 + $diff;
return gmdate( 'Y-m-d', $start ) . ',' . gmdate( 'Y-m-d', $end );
}
}

View File

@ -1,63 +1,74 @@
<?php <?php
namespace WP_Piwik\Template; namespace WP_Piwik\Template;
class MetaBoxCustomVars extends \WP_Piwik\Template { class MetaBoxCustomVars extends \WP_Piwik\Template {
public function addMetabox() { public function addMetabox() {
add_meta_box( add_meta_box(
'wp-piwik_post_customvars', 'wp-piwik_post_customvars',
__('Piwik Custom Variables', 'wp-piwik'), __( 'Piwik Custom Variables', 'wp-piwik' ),
array(&$this, 'showCustomvars'), array( &$this, 'showCustomvars' ),
array('post', 'page', 'custom_post_type'), array( 'post', 'page', 'custom_post_type' ),
'side', 'side',
'default' 'default'
); );
} }
public function showCustomvars($objPost, $objBox ) { public function showCustomvars( $obj_post, $obj_box ) {
wp_nonce_field(basename( __FILE__ ), 'wp-piwik_post_customvars_nonce'); ?> wp_nonce_field( basename( __FILE__ ), 'wp-piwik_post_customvars_nonce' ); ?>
<table> <table>
<tr><th></th><th><?php _e('Name', 'wp-piwik'); ?></th><th><?php _e('Value', 'wp-piwik'); ?></th></tr> <tr><th></th><th><?php esc_html_e( 'Name', 'wp-piwik' ); ?></th><th><?php esc_html_e( 'Value', 'wp-piwik' ); ?></th></tr>
<?php for($i = 1; $i <= 5; $i++) { ?> <?php for ( $i = 1; $i <= 5; $i++ ) { ?>
<tr> <tr>
<th><label for="wp-piwik_customvar1"><?php echo $i; ?>: </label></th> <th><label for="wp-piwik_customvar1"><?php echo esc_attr( $i ); // @phpstan-ignore-line ?>: </label></th>
<td><input class="widefat" type="text" name="wp-piwik_custom_cat<?php echo $i; ?>" value="<?php echo esc_attr(get_post_meta($objPost->ID, 'wp-piwik_custom_cat'.$i, true ) ); ?>" size="200" /></td> <td><input class="widefat" type="text" name="wp-piwik_custom_cat<?php echo esc_attr( $i ); // @phpstan-ignore-line ?>" value="<?php echo esc_attr( get_post_meta( $obj_post->ID, 'wp-piwik_custom_cat' . $i, true ) ); ?>" size="200" /></td>
<td><input class="widefat" type="text" name="wp-piwik_custom_val<?php echo $i; ?>" value="<?php echo esc_attr(get_post_meta($objPost->ID, 'wp-piwik_custom_val'.$i, true ) ); ?>" size="200" /></td> <td><input class="widefat" type="text" name="wp-piwik_custom_val<?php echo esc_attr( $i ); // @phpstan-ignore-line ?>" value="<?php echo esc_attr( get_post_meta( $obj_post->ID, 'wp-piwik_custom_val' . $i, true ) ); ?>" size="200" /></td>
</tr> </tr>
<?php } ?> <?php } ?>
</table> </table>
<p><?php _e('Set custom variables for a page view', 'wp-piwik'); ?>. (<a href="http://piwik.org/docs/custom-variables/"><?php _e('More information', 'wp-piwik'); ?></a>.)</p> <p><?php esc_html_e( 'Set custom variables for a page view', 'wp-piwik' ); ?>. (<a href="http://piwik.org/docs/custom-variables/"><?php esc_html_e( 'More information', 'wp-piwik' ); ?></a>.)</p>
<?php <?php
} }
public function saveCustomVars($intID, $objPost) { public function saveCustomVars( $int_id, $obj_post ) {
// Verify the nonce before proceeding. // Verify the nonce before proceeding.
if (!isset( $_POST['wp-piwik_post_customvars_nonce'] ) || !wp_verify_nonce( $_POST['wp-piwik_post_customvars_nonce'], basename( __FILE__ ) ) ) $nonce = isset( $_POST['wp-piwik_post_customvars_nonce'] )
return $intID; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
// Get post type object ? wp_unslash( $_POST['wp-piwik_post_customvars_nonce'] )
$objPostType = get_post_type_object($objPost->post_type); : '';
// Check if the current user has permission to edit the post. if (
if (!current_user_can($objPostType->cap->edit_post, $intID)) empty( $nonce )
return $intID; || ! wp_verify_nonce( $nonce, basename( __FILE__ ) )
$aryNames = array('cat', 'val'); ) {
for ($i = 1; $i <= 5; $i++) return $int_id;
for ($j = 0; $j <= 1; $j++) { }
// Get data // Get post type object
$strMetaVal = (isset($_POST['wp-piwik_custom_'.$aryNames[$j].$i])?htmlentities($_POST['wp-piwik_custom_'.$aryNames[$j].$i]):''); $obj_post_type = get_post_type_object( $obj_post->post_type );
// Create key // Check if the current user has permission to edit the post.
$strMetaKey = 'wp-piwik_custom_'.$aryNames[$j].$i; if ( ! current_user_can( $obj_post_type->cap->edit_post, $int_id ) ) {
// Get the meta value of the custom field key return $int_id;
$strCurVal = get_post_meta($intID, $strMetaKey, true); }
$ary_names = array( 'cat', 'val' );
for ( $i = 1; $i <= 5; $i++ ) {
for ( $j = 0; $j <= 1; $j++ ) {
// Create key
$str_meta_key = 'wp-piwik_custom_' . $ary_names[ $j ] . $i;
// Get data
$str_meta_val = isset( $_POST[ $str_meta_key ] ) ? esc_html( $str_meta_key ) : '';
// Get the meta value of the custom field key
$str_cur_val = get_post_meta( $int_id, $str_meta_key, true );
if ( $str_meta_val && '' === $str_cur_val ) {
// Add meta val: // Add meta val:
if ($strMetaVal && '' == $strCurVal) add_post_meta( $int_id, $str_meta_key, $str_meta_val, true );
add_post_meta($intID, $strMetaKey, $strMetaVal, true); } elseif ( $str_meta_val && $str_meta_val !== $str_cur_val ) {
// Update meta val: // Update meta val:
elseif ($strMetaVal && $strMetaVal != $strCurVal) update_post_meta( $int_id, $str_meta_key, $str_meta_val );
update_post_meta($intID, $strMetaKey, $strMetaVal); } elseif ( '' === $str_meta_val && $str_cur_val ) {
// Delete meta val: // Delete meta val:
elseif (''==$strMetaVal && $strCurVal) delete_post_meta( $int_id, $str_meta_key, $str_cur_val );
delete_post_meta($intID, $strMetaKey, $strCurVal);
} }
}
} }
} }
}

View File

@ -4,164 +4,261 @@ namespace WP_Piwik;
class TrackingCode { class TrackingCode {
private static $wpPiwik, $piwikUrl = false; /**
* @var \WP_Piwik
*/
private static $wp_piwik;
private $trackingCode; private $tracking_code;
public $is404 = false, $isSearch = false, $isUsertracking = false; public $is_404 = false;
public $is_search = false;
public $is_usertracking = false;
public function __construct($wpPiwik) { public function __construct( $wp_piwik ) {
self::$wpPiwik = $wpPiwik; self::$wp_piwik = $wp_piwik;
if (! self::$wpPiwik->isCurrentTrackingCode () || ! self::$wpPiwik->getOption ( 'tracking_code' ) || strpos( self::$wpPiwik->getOption ( 'tracking_code' ), '{"result":"error",' ) !== false ) if ( ! self::$wp_piwik->is_current_tracking_code() || ! self::$wp_piwik->get_option( 'tracking_code' ) || strpos( self::$wp_piwik->get_option( 'tracking_code' ), '{"result":"error",' ) !== false ) {
self::$wpPiwik->updateTrackingCode (); self::$wp_piwik->update_tracking_code();
$this->trackingCode = (self::$wpPiwik->isNetworkMode () && self::$wpPiwik->getGlobalOption ( 'track_mode' ) == 'manually') ? get_site_option ( 'wp-piwik-manually' ) : self::$wpPiwik->getOption ( 'tracking_code' ); }
$this->tracking_code = ( self::$wp_piwik->is_network_mode() && self::$wp_piwik->get_global_option( 'track_mode' ) === 'manually' ) ? get_site_option( 'wp-piwik-manually' ) : self::$wp_piwik->get_option( 'tracking_code' );
} }
public function getTrackingCode() { public function get_tracking_code() {
if ($this->isUsertracking) if ( $this->is_usertracking ) {
$this->applyUserTracking (); $this->apply_user_tracking();
if ($this->is404) }
$this->apply404Changes (); if ( $this->is_404 ) {
if ($this->isSearch) $this->apply_404_changes();
$this->applySearchChanges (); }
if (is_single () || is_page()) if ( $this->is_search ) {
$this->addCustomValues (); $this->apply_search_changes();
$this->trackingCode = apply_filters('wp-piwik_tracking_code', $this->trackingCode); }
return $this->trackingCode; if ( is_single() || is_page() ) {
$this->add_custom_values();
}
// ignoring for BC
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
// phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
$this->tracking_code = apply_filters( 'wp-piwik_tracking_code', $this->tracking_code );
return $this->tracking_code;
} }
public static function prepareTrackingCode($code, $settings, $logger) { /**
* @param string $code
* @param Settings $settings
* @param Logger $logger
* @return array
*/
public static function prepare_tracking_code( $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->set_option( 'last_tracking_code_update', (string) time() );
if (preg_match ( '/var u="([^"]*)";/', $code, $hits )) { if ( preg_match( '/var u="([^"]*)";/', $code, $hits ) ) {
$fetchedProxyUrl = $hits [1]; $fetched_proxy_url = $hits [1];
} else $fetchedProxyUrl = ''; } else {
if ($settings->getGlobalOption ( 'remove_type_attribute')) { $fetched_proxy_url = '';
$code = str_replace ( }
array( ' type="text/javascript"', " type='text/javascript'" ), if ( $settings->get_global_option( 'remove_type_attribute' ) ) {
'', $code = str_replace(
$code array( ' type="text/javascript"', " type='text/javascript'" ),
); '',
} $code
if ($settings->getGlobalOption ( 'track_mode' ) == 'js') );
$code = str_replace ( array ( }
if ( 'js' === $settings->get_global_option( 'track_mode' ) ) {
$code = str_replace(
array(
'piwik.js', 'piwik.js',
'piwik.php', 'piwik.php',
'matomo.js', 'matomo.js',
'matomo.php' 'matomo.php',
), 'js/index.php', $code ); ),
elseif ($settings->getGlobalOption ( 'track_mode' ) == 'proxy') { 'js/index.php',
$code = str_replace ( 'piwik.js', 'matomo.php', $code ); $code
$code = str_replace ( 'matomo.js', 'matomo.php', $code ); );
$code = str_replace ( 'piwik.php', 'matomo.php', $code ); } elseif ( 'proxy' === $settings->get_global_option( 'track_mode' ) ) {
$proxy = str_replace ( array ( $code = str_replace( 'piwik.js', 'matomo.php', $code );
$code = str_replace( 'matomo.js', 'matomo.php', $code );
$code = str_replace( 'piwik.php', 'matomo.php', $code );
$proxy = str_replace(
array(
'https://', 'https://',
'http://' 'http://',
), '//', plugins_url ( 'wp-piwik' ) . '/proxy' ) . '/'; ),
$code = preg_replace ( '/var u="([^"]*)";/', 'var u="' . $proxy . '"', $code ); '//',
$code = preg_replace ( '/img src="([^"]*)piwik.php/', 'img src="' . $proxy . 'matomo.php', $code ); plugins_url( 'wp-piwik' ) . '/proxy'
$code = preg_replace ( '/img src="([^"]*)matomo.php/', 'img src="' . $proxy . 'matomo.php', $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="([^"]*)matomo.php/', 'img src="' . $proxy . 'matomo.php', $code );
}
if ( $settings->get_global_option( 'track_cdnurl' ) || $settings->get_global_option( 'track_cdnurlssl' ) ) {
$code = str_replace(
array(
'var d=doc',
'g.src=u+',
),
array(
"var ucdn=(('https:' == document.location.protocol) ? 'https://" . ( $settings->get_global_option( 'track_cdnurlssl' ) ? $settings->get_global_option( 'track_cdnurlssl' ) : $settings->get_global_option( 'track_cdnurl' ) ) . "/' : 'http://" . ( $settings->get_global_option( 'track_cdnurl' ) ? $settings->get_global_option( 'track_cdnurl' ) : $settings->get_global_option( 'track_cdnurlssl' ) ) . "/');\nvar d=doc",
'g.src=ucdn+',
),
$code
);
} }
if ($settings->getGlobalOption ( 'track_cdnurl' ) || $settings->getGlobalOption ( 'track_cdnurlssl' ))
$code = str_replace ( array (
"var d=doc",
"g.src=u+"
), array (
"var ucdn=(('https:' == document.location.protocol) ? 'https://" . ($settings->getGlobalOption ( 'track_cdnurlssl' ) ? $settings->getGlobalOption ( 'track_cdnurlssl' ) : $settings->getGlobalOption ( 'track_cdnurl' )) . "/' : 'http://" . ($settings->getGlobalOption ( 'track_cdnurl' ) ? $settings->getGlobalOption ( 'track_cdnurl' ) : $settings->getGlobalOption ( 'track_cdnurlssl' )) . "/');\nvar d=doc",
"g.src=ucdn+"
), $code );
if ($settings->getGlobalOption ( 'track_datacfasync' )) if ( $settings->get_global_option( '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' )) }
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['setDownloadExtensions', '" . ($settings->getGlobalOption ( 'set_download_extensions' )) . "']);\n_paq.push(['trackPageView']);", $code );
if ($settings->getGlobalOption ( 'add_download_extensions' ))
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['addDownloadExtensions', '" . ($settings->getGlobalOption ( 'add_download_extensions' )) . "']);\n_paq.push(['trackPageView']);", $code );
if ($settings->getGlobalOption ( 'set_download_classes' ))
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['setDownloadClasses', '" . ($settings->getGlobalOption ( 'set_download_classes' )) . "']);\n_paq.push(['trackPageView']);", $code );
if ($settings->getGlobalOption ( 'set_link_classes' ))
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['setLinkClasses', '" . ($settings->getGlobalOption ( 'set_link_classes' )) . "']);\n_paq.push(['trackPageView']);", $code );
if ($settings->getGlobalOption ( 'limit_cookies' ))
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['setVisitorCookieTimeout', '" . $settings->getGlobalOption ( 'limit_cookies_visitor' ) . "']);\n_paq.push(['setSessionCookieTimeout', '" . $settings->getGlobalOption ( 'limit_cookies_session' ) . "']);\n_paq.push(['setReferralCookieTimeout', '" . $settings->getGlobalOption ( 'limit_cookies_referral' ) . "']);\n_paq.push(['trackPageView']);", $code );
if ($settings->getGlobalOption ( 'force_protocol' ) != 'disabled')
$code = str_replace ( '"//', '"' . $settings->getGlobalOption ( 'force_protocol' ) . '://', $code );
if ($settings->getGlobalOption ( 'track_content' ) == 'all')
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['trackPageView']);\n_paq.push(['trackAllContentImpressions']);", $code );
elseif ($settings->getGlobalOption ( 'track_content' ) == 'visible')
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['trackPageView']);\n_paq.push(['trackVisibleContentImpressions']);", $code );
if ((int) $settings->getGlobalOption ( 'track_heartbeat' ) > 0)
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['trackPageView']);\n_paq.push(['enableHeartBeatTimer', ".(int) $settings->getGlobalOption ( 'track_heartbeat' )."]);", $code );
if ($settings->getGlobalOption ( 'require_consent' ) == 'consent') {
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['requireConsent']);\n_paq.push(['trackPageView']);", $code );
} elseif ($settings->getGlobalOption ( 'require_consent' ) == 'cookieconsent') {
$code = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['requireCookieConsent']);\n_paq.push(['trackPageView']);", $code );
}
$noScript = array (); if ( $settings->is_ai_bot_tracking_enabled() ) {
preg_match ( '/<noscript>(.*)<\/noscript>/', $code, $noScript ); // recMode is a temporary parameter introduced in core to conditionally
if (isset ( $noScript [0] )) { // enable AI bot tracking. if AI bot tracking is enabled in Connect Matomo,
if ($settings->getGlobalOption ( 'track_nojavascript' )) // we set it to `2` here, to enable "auto" mode when doing JS tracking. in
$noScript [0] = str_replace ( '?idsite', '?rec=1&idsite', $noScript [0] ); // this mode, tracking requests with AI bot user agents will be tracked as
$noScript = $noScript [0]; // bots instead of visits, while all other requests will be tracked normally
} else // as visits.
$noScript = ''; $code = str_replace(
$script = preg_replace ( '/<noscript>(.*)<\/noscript>/', '', $code ); "_paq.push(['trackPageView']);",
$script = preg_replace ( '/\s+(\r\n|\r|\n)/', '$1', $script ); "_paq.push(['appendToTrackingUrl', 'recMode=2']);\n_paq.push(['trackPageView']);",
$logger->log ( 'Finished tracking code: ' . $script ); $code
$logger->log ( 'Finished noscript code: ' . $noScript ); );
return array (
'script' => $script, // set cookie via javascript cookie for known AI bots so we can skip tracking server side
'noscript' => $noScript, // for them.
'proxy' => $fetchedProxyUrl // NOTE: this must be done ONLY for known AI bots to be compliant with privacy regulations.
$user_agent_substrings = wp_json_encode( AjaxTracker::AI_BOT_USER_AGENT_SUBSTRINGS );
$cookie_set_fn = <<<EOF
_paq.push([ function () {
var userAgentSubstrings = $user_agent_substrings;
for (var i = 0; i < userAgentSubstrings.length; ++i) {
var isAiBotUserAgent = navigator.userAgent.toLowerCase().indexOf(userAgentSubstrings[i].toLowerCase()) !== -1;
if (isAiBotUserAgent) {
var path = this.getCookiePath();
var domain = this.getCookieDomain();
var sameSite = 'Lax';
document.cookie = 'matomo_has_js=1;path=' +
(path || '/') +
(domain ? ';domain=' + domain : '') +
';SameSite=' + sameSite
;
return;
}
}
} ]);
EOF;
$code = str_replace(
"_paq.push(['trackPageView']);",
$cookie_set_fn . "\n_paq.push(['trackPageView']);",
$code
);
}
if ( $settings->get_global_option( 'set_download_extensions' ) ) {
$code = str_replace( "_paq.push(['trackPageView']);", "_paq.push(['setDownloadExtensions', " . wp_json_encode( $settings->get_global_option( 'set_download_extensions' ) ) . "]);\n_paq.push(['trackPageView']);", $code );
}
if ( $settings->get_global_option( 'add_download_extensions' ) ) {
$code = str_replace( "_paq.push(['trackPageView']);", "_paq.push(['addDownloadExtensions', " . wp_json_encode( $settings->get_global_option( 'add_download_extensions' ) ) . "]);\n_paq.push(['trackPageView']);", $code );
}
if ( $settings->get_global_option( 'set_download_classes' ) ) {
$code = str_replace( "_paq.push(['trackPageView']);", "_paq.push(['setDownloadClasses', " . wp_json_encode( $settings->get_global_option( 'set_download_classes' ) ) . "]);\n_paq.push(['trackPageView']);", $code );
}
if ( $settings->get_global_option( 'set_link_classes' ) ) {
$code = str_replace( "_paq.push(['trackPageView']);", "_paq.push(['setLinkClasses', " . wp_json_encode( $settings->get_global_option( 'set_link_classes' ) ) . "]);\n_paq.push(['trackPageView']);", $code );
}
if ( $settings->get_global_option( 'limit_cookies' ) ) {
$code = str_replace( "_paq.push(['trackPageView']);", "_paq.push(['setVisitorCookieTimeout', " . wp_json_encode( $settings->get_global_option( 'limit_cookies_visitor' ) ) . "]);\n_paq.push(['setSessionCookieTimeout', " . wp_json_encode( $settings->get_global_option( 'limit_cookies_session' ) ) . "]);\n_paq.push(['setReferralCookieTimeout', " . wp_json_encode( $settings->get_global_option( 'limit_cookies_referral' ) ) . "]);\n_paq.push(['trackPageView']);", $code );
}
if ( 'disabled' !== $settings->get_global_option( 'force_protocol' ) ) {
$code = str_replace( '"//', '"' . $settings->get_global_option( 'force_protocol' ) . '://', $code );
}
if ( 'all' === $settings->get_global_option( 'track_content' ) ) {
$code = str_replace( "_paq.push(['trackPageView']);", "_paq.push(['trackPageView']);\n_paq.push(['trackAllContentImpressions']);", $code );
} elseif ( 'visible' === $settings->get_global_option( 'track_content' ) ) {
$code = str_replace( "_paq.push(['trackPageView']);", "_paq.push(['trackPageView']);\n_paq.push(['trackVisibleContentImpressions']);", $code );
}
if ( (int) $settings->get_global_option( 'track_heartbeat' ) > 0 ) {
$code = str_replace( "_paq.push(['trackPageView']);", "_paq.push(['trackPageView']);\n_paq.push(['enableHeartBeatTimer', " . (int) $settings->get_global_option( 'track_heartbeat' ) . ']);', $code );
}
if ( 'consent' === $settings->get_global_option( 'require_consent' ) ) {
$code = str_replace( "_paq.push(['trackPageView']);", "_paq.push(['requireConsent']);\n_paq.push(['trackPageView']);", $code );
} elseif ( 'cookieconsent' === $settings->get_global_option( 'require_consent' ) ) {
$code = str_replace( "_paq.push(['trackPageView']);", "_paq.push(['requireCookieConsent']);\n_paq.push(['trackPageView']);", $code );
}
$no_script = array();
preg_match( '/<noscript>(.*)<\/noscript>/', $code, $no_script );
if ( isset( $no_script [0] ) ) {
if ( $settings->get_global_option( 'track_nojavascript' ) ) {
$no_script [0] = str_replace( '?idsite', '?rec=1&idsite', $no_script [0] );
}
$no_script = $no_script [0];
} else {
$no_script = '';
}
$script = preg_replace( '/<noscript>(.*)<\/noscript>/', '', $code );
$script = preg_replace( '/\s+(\r\n|\r|\n)/', '$1', $script );
$logger->log( 'Finished tracking code: ' . $script );
$logger->log( 'Finished noscript code: ' . $no_script );
return array(
'script' => $script,
'noscript' => $no_script,
'proxy' => $fetched_proxy_url,
); );
} }
private function apply404Changes() { private function apply_404_changes() {
self::$wpPiwik->log ( 'Apply 404 changes. Blog ID: ' . get_current_blog_id () . ' Site ID: ' . self::$wpPiwik->getOption ( 'site_id' ) ); self::$wp_piwik->log( 'Apply 404 changes. Blog ID: ' . get_current_blog_id() . ' Site ID: ' . self::$wp_piwik->get_option( '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->tracking_code = 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->tracking_code );
} }
private function applySearchChanges() { private function apply_search_changes() {
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::$wp_piwik->log( 'Apply search tracking changes. Blog ID: ' . get_current_blog_id() . ' Site ID: ' . self::$wp_piwik->get_option( 'site_id' ) );
$intResultCount = $wp_query->found_posts; $int_result_count = $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->tracking_code = str_replace( "_paq.push(['trackPageView']);", "_paq.push(['trackSiteSearch','" . get_search_query() . "', false, " . $int_result_count . "]);\n_paq.push(['trackPageView']);", $this->tracking_code );
} }
private function applyUserTracking() { private function apply_user_tracking() {
$pkUserId = null; $pk_user_id = 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' ); $uid_from = self::$wp_piwik->get_global_option( '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 ( 'uid' === $uid_from ) {
$pkUserId = $current_user->ID; $pk_user_id = $current_user->ID;
} elseif ( $uidFrom == 'email' ) { } elseif ( 'email' === $uid_from ) {
$pkUserId = $current_user->user_email; $pk_user_id = $current_user->user_email;
} elseif ( $uidFrom == 'username' ) { } elseif ( 'username' === $uid_from ) {
$pkUserId = $current_user->user_login; $pk_user_id = $current_user->user_login;
} elseif ( $uidFrom == 'displayname' ) { } elseif ( 'displayname' === $uid_from ) {
$pkUserId = $current_user->display_name; $pk_user_id = $current_user->display_name;
} }
} }
$pkUserId = apply_filters('wp-piwik_tracking_user_id', $pkUserId); // ignoring for BC
// Check we got a User ID to track, and track it // phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
if ( isset( $pkUserId ) && ! empty( $pkUserId )) // phpcs:ignore WordPress.NamingConventions.ValidHookName.UseUnderscores
$this->trackingCode = str_replace ( "_paq.push(['trackPageView']);", "_paq.push(['setUserId', '" . esc_js( $pkUserId ) . "']);\n_paq.push(['trackPageView']);", $this->trackingCode ); $pk_user_id = apply_filters( 'wp-piwik_tracking_user_id', $pk_user_id );
// Check we got a User ID to track, and track it
if ( isset( $pk_user_id ) && ! empty( $pk_user_id ) ) {
$this->tracking_code = str_replace( "_paq.push(['trackPageView']);", "_paq.push(['setUserId', '" . esc_js( $pk_user_id ) . "']);\n_paq.push(['trackPageView']);", $this->tracking_code );
}
} }
private function addCustomValues() { private function add_custom_values() {
$customVars = ''; $custom_vars = '';
for($i = 1; $i <= 5; $i ++) { for ( $i = 1; $i <= 5; $i++ ) {
$postId = get_the_ID (); $post_id = get_the_ID();
$metaKey = get_post_meta ( $postId, 'wp-piwik_custom_cat' . $i, true ); $meta_key = get_post_meta( $post_id, 'wp-piwik_custom_cat' . $i, true );
$metaVal = get_post_meta ( $postId, 'wp-piwik_custom_val' . $i, true ); $meta_val = get_post_meta( $post_id, 'wp-piwik_custom_val' . $i, true );
if (! empty ( $metaKey ) && ! empty ( $metaVal )) if ( ! empty( $meta_key ) && ! empty( $meta_val ) ) {
$customVars .= "_paq.push(['setCustomVariable'," . $i . ", '" . $metaKey . "', '" . $metaVal . "', 'page']);\n"; $custom_vars .= "_paq.push(['setCustomVariable'," . $i . ', ' . wp_json_encode( $meta_key ) . ', ' . wp_json_encode( $meta_val ) . ", 'page']);\n";
}
}
if ( ! empty( $custom_vars ) ) {
$this->tracking_code = str_replace( "_paq.push(['trackPageView']);", $custom_vars . "_paq.push(['trackPageView']);", $this->tracking_code );
} }
if (! empty ( $customVars ))
$this->trackingCode = str_replace ( "_paq.push(['trackPageView']);", $customVars . "_paq.push(['trackPageView']);", $this->trackingCode );
} }
} }

View File

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

View File

@ -1,70 +1,80 @@
<?php <?php
namespace WP_Piwik\Widget; namespace WP_Piwik\Widget;
use WP_Piwik\Widget; use WP_Piwik\Widget;
class BrowserDetails extends Widget { class BrowserDetails extends Widget {
public $className = __CLASS__; public $class_name = __CLASS__;
protected function configure($prefix = '', $params = array()) { protected function configure( $prefix = '', $params = array() ) {
$timeSettings = $this->getTimeSettings(); $time_settings = $this->get_time_settings();
$this->parameter = array( $this->parameter = array(
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId), 'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
'period' => $timeSettings['period'], 'period' => $time_settings['period'],
'date' => $timeSettings['date'] 'date' => $time_settings['date'],
); );
$this->title = $prefix.__('Browser Details', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')'; $this->title = $prefix . __( 'Browser Details', 'wp-piwik' ) . ' (' . $time_settings['description'] . ')';
$this->method = 'DevicesDetection.getBrowserVersions'; $this->method = 'DevicesDetection.getBrowserVersions';
$this->context = 'normal'; $this->context = 'normal';
wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
wp_enqueue_script ( 'wp-piwik-chartjs', self::$wpPiwik->getPluginURL () . 'js/chartjs/chart.min.js', "3.4.1" );
wp_enqueue_style('wp-piwik', self::$wpPiwik->getPluginURL().'css/wp-piwik.css',array(),self::$wpPiwik->getPluginVersion());
}
public function show() {
$response = self::$wpPiwik->request($this->apiID[$this->method]);
$tableBody = array();
if (!empty($response['result']) && $response['result'] ='error')
echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
else {
$tableHead = array(__('Browser', 'wp-piwik'), __('Unique', 'wp-piwik'), __('Percent', 'wp-piwik'));
if (isset($response[0]['nb_uniq_visitors'])) $unique = 'nb_uniq_visitors';
else $unique = 'sum_daily_nb_uniq_visitors';
$count = 0;
$sum = 0;
$js = array();
$class = array();
if (is_array($response))
foreach ($response as $row) {
$count++;
$sum += isset($row[$unique])?$row[$unique]:0;
if ($count < $this->limit)
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
elseif (!isset($tableBody['Others'])) {
$tableBody['Others'] = array($row['label'], $row[$unique], 0);
$class['Others'] = 'wp-piwik-hideDetails';
$js['Others'] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
$class[$row['label']] = 'wp-piwik-hideDetails hidden';
$js[$row['label']] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
} else {
$tableBody['Others'][1] += $row[$unique];
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
$class[$row['label']] = 'wp-piwik-hideDetails hidden';
$js[$row['label']] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
}
}
if ($count > $this->limit)
$tableBody['Others'][0] = __('Others', 'wp-piwik');
foreach ($tableBody as $key => $row)
$tableBody[$key][2] = number_format($row[1]/$sum*100, 2).'%';
if (!empty($tableBody)) $this->pieChart($tableBody);
$this->table($tableHead, $tableBody, null, false, $js, $class);
}
}
$version = self::$wp_piwik->get_plugin_version();
wp_enqueue_script( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'js/wp-piwik.js', array(), $version, true );
wp_enqueue_script( 'wp-piwik-chartjs', self::$wp_piwik->get_plugin_url() . 'js/chartjs/chart.min.js', array(), $version, false );
wp_enqueue_style( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'css/wp-piwik.css', array(), $version );
} }
public function show() {
$response = self::$wp_piwik->request( $this->api_id[ $this->method ] );
$table_body = array();
if ( ! empty( $response['result'] ) && 'error' === $response['result'] ) {
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $response['message'] );
} else {
$table_head = array( __( 'Browser', 'wp-piwik' ), __( 'Unique', 'wp-piwik' ), __( 'Percent', 'wp-piwik' ) );
if ( isset( $response[0]['nb_uniq_visitors'] ) ) {
$unique = 'nb_uniq_visitors';
} else {
$unique = 'sum_daily_nb_uniq_visitors';
}
$count = 0;
$sum = 0;
$js = array();
$css_class = array();
if ( is_array( $response ) ) {
foreach ( $response as $row ) {
++$count;
$sum += isset( $row[ $unique ] ) ? $row[ $unique ] : 0;
if ( $count < $this->limit ) {
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
} elseif ( ! isset( $table_body['Others'] ) ) {
$table_body['Others'] = array( $row['label'], $row[ $unique ], 0 );
$css_class['Others'] = 'wp-piwik-hideDetails';
$js['Others'] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
$css_class[ $row['label'] ] = 'wp-piwik-hideDetails hidden';
$js[ $row['label'] ] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
} else {
$table_body['Others'][1] += $row[ $unique ];
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
$css_class[ $row['label'] ] = 'wp-piwik-hideDetails hidden';
$js[ $row['label'] ] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
}
}
}
if ( $count > $this->limit ) {
$table_body['Others'][0] = __( 'Others', 'wp-piwik' );
}
foreach ( $table_body as $key => $row ) {
$table_body[ $key ][2] = number_format( $row[1] / $sum * 100, 2 ) . '%';
}
if ( ! empty( $table_body ) ) {
$this->pie_chart( $table_body );
}
$this->table( $table_head, $table_body, null, false, $js, $css_class );
}
}
}

View File

@ -1,73 +1,83 @@
<?php <?php
namespace WP_Piwik\Widget; namespace WP_Piwik\Widget;
use WP_Piwik\Widget; use WP_Piwik\Widget;
class Browsers extends Widget { class Browsers extends Widget {
public $className = __CLASS__; public $class_name = __CLASS__;
protected function configure($prefix = '', $params = array()) { protected function configure( $prefix = '', $params = array() ) {
$timeSettings = $this->getTimeSettings(); $time_settings = $this->get_time_settings();
$this->parameter = array( $this->parameter = array(
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId), 'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
'period' => $timeSettings['period'], 'period' => $time_settings['period'],
'date' => $timeSettings['date'] 'date' => $time_settings['date'],
); );
$this->title = $prefix.__('Browsers', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')'; $this->title = $prefix . __( 'Browsers', 'wp-piwik' ) . ' (' . $time_settings['description'] . ')';
$this->method = 'DevicesDetection.getBrowsers'; $this->method = 'DevicesDetection.getBrowsers';
$this->context = 'normal'; $this->context = 'normal';
wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
wp_enqueue_script ( 'wp-piwik-chartjs', self::$wpPiwik->getPluginURL () . 'js/chartjs/chart.min.js', "3.4.1" );
wp_enqueue_style('wp-piwik', self::$wpPiwik->getPluginURL().'css/wp-piwik.css',array(),self::$wpPiwik->getPluginVersion());
}
public function show() {
$response = self::$wpPiwik->request($this->apiID[$this->method]);
$tableBody = array();
if (!empty($response['result']) && $response['result'] ='error')
echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
else {
$tableHead = array(__('Browser', 'wp-piwik'), __('Unique', 'wp-piwik'), __('Percent', 'wp-piwik'));
if (isset($response[0]['nb_uniq_visitors'])) $unique = 'nb_uniq_visitors';
else $unique = 'sum_daily_nb_uniq_visitors';
$count = 0;
$sum = 0;
$js = array();
$class = array();
if (is_array($response))
foreach ($response as $row) {
$count++;
$sum += isset($row[$unique])?$row[$unique]:0;
if ($count < $this->limit)
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
elseif (!isset($tableBody['Others'])) {
$tableBody['Others'] = array($row['label'], $row[$unique], 0);
$class['Others'] = 'wp-piwik-hideDetails';
$js['Others'] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
$class[$row['label']] = 'wp-piwik-hideDetails hidden';
$js[$row['label']] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
} else {
$tableBody['Others'][1] += $row[$unique];
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
$class[$row['label']] = 'wp-piwik-hideDetails hidden';
$js[$row['label']] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
}
}
if ($count > $this->limit)
$tableBody['Others'][0] = __('Others', 'wp-piwik');
elseif ($count == $this->limit) {
$class['Others'] = $js['Others'] = '';
}
foreach ($tableBody as $key => $row)
$tableBody[$key][2] = number_format($row[1]/$sum*100, 2).'%';
if (!empty($tableBody)) $this->pieChart($tableBody);
$this->table($tableHead, $tableBody, null, false, $js, $class);
}
}
$version = self::$wp_piwik->get_plugin_version();
wp_enqueue_script( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'js/wp-piwik.js', array(), $version, true );
wp_enqueue_script( 'wp-piwik-chartjs', self::$wp_piwik->get_plugin_url() . 'js/chartjs/chart.min.js', array(), $version, false );
wp_enqueue_style( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'css/wp-piwik.css', array(), $version );
} }
public function show() {
$response = self::$wp_piwik->request( $this->api_id[ $this->method ] );
$table_body = array();
if ( ! empty( $response['result'] ) && 'error' === $response['result'] ) {
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $response['message'] );
} else {
$table_head = array( __( 'Browser', 'wp-piwik' ), __( 'Unique', 'wp-piwik' ), __( 'Percent', 'wp-piwik' ) );
if ( isset( $response[0]['nb_uniq_visitors'] ) ) {
$unique = 'nb_uniq_visitors';
} else {
$unique = 'sum_daily_nb_uniq_visitors';
}
$count = 0;
$sum = 0;
$js = array();
$css_class = array();
if ( is_array( $response ) ) {
foreach ( $response as $row ) {
++$count;
$sum += isset( $row[ $unique ] ) ? $row[ $unique ] : 0;
if ( $count < $this->limit ) {
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
} elseif ( ! isset( $table_body['Others'] ) ) {
$table_body['Others'] = array( $row['label'], $row[ $unique ], 0 );
$css_class['Others'] = 'wp-piwik-hideDetails';
$js['Others'] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
$css_class[ $row['label'] ] = 'wp-piwik-hideDetails hidden';
$js[ $row['label'] ] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
} else {
$table_body['Others'][1] += $row[ $unique ];
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
$css_class[ $row['label'] ] = 'wp-piwik-hideDetails hidden';
$js[ $row['label'] ] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
}
}
}
if ( $count > $this->limit ) {
$table_body['Others'][0] = __( 'Others', 'wp-piwik' );
} elseif ( $count === $this->limit ) {
$css_class['Others'] = '';
$js['Others'] = '';
}
foreach ( $table_body as $key => $row ) {
$table_body[ $key ][2] = number_format( $row[1] / $sum * 100, 2 ) . '%';
}
if ( ! empty( $table_body ) ) {
$this->pie_chart( $table_body );
}
$this->table( $table_head, $table_body, null, false, $js, $css_class );
}
}
}

View File

@ -4,85 +4,97 @@ namespace WP_Piwik\Widget;
use WP_Piwik\Widget; use WP_Piwik\Widget;
class Chart extends Visitors class Chart extends Visitors {
{
public $className = __CLASS__; public $class_name = __CLASS__;
public function show() public function show() {
{ $result = $this->request_data();
$result = $this->requestData(); $response = $result['response'];
$response = $result["response"]; if ( ! $result['success'] ) {
if (!$result["success"]) { $message = '';
echo '<strong>' . __('Piwik error', 'wp-piwik') . ':</strong> ' . htmlentities($response[$method]['message'], ENT_QUOTES, 'utf-8'); if ( is_array( $this->method ) ) {
} else { foreach ( $this->method as $m ) {
$values = $labels = $bounced = $unique = ''; if ( empty( $response[ $m ]['message'] ) ) {
$count = $uniqueSum = 0; continue;
if (is_array($response['VisitsSummary.getVisits'])) }
foreach ($response['VisitsSummary.getVisits'] as $date => $value) {
$count++;
$values .= $value . ',';
$unique .= $response['VisitsSummary.getUniqueVisitors'][$date] . ',';
$bounced .= $response['VisitsSummary.getBounceCount'][$date] . ',';
if ($this->parameter['period'] == 'week') {
preg_match("/[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/", $date, $dateList);
$textKey = $this->dateFormat($dateList[0], 'short_week');
} else $textKey = substr($date, -2);
$labels .= '["' . $textKey . '"],';
$uniqueSum += $response['VisitsSummary.getActions'][$date];
}
else {
$values = '0,';
$labels = '[0,"-"],';
$unique = '0,';
$bounced = '0,';
}
$average = round($uniqueSum / 30, 0);
$values = substr($values, 0, -1);
$unique = substr($unique, 0, -1);
$labels = substr($labels, 0, -1);
$bounced = substr($bounced, 0, -1);
?>
<div>
<canvas id="wp-piwik_stats_vistors_graph" style="height:220px;"></canvas>
</div>
<script>
new Chart(
document.getElementById('wp-piwik_stats_vistors_graph'),
{
type: 'line',
data: {
labels: [<?php echo $labels ?>],
datasets: [
{
label: 'Visitors',
backgroundColor: '#0277bd',
borderColor: '#0277bd',
data: [<?php echo $values; ?>],
borderWidth: 1
},
{
label: 'Unique',
backgroundColor: '#ff8f00',
borderColor: '#ff8f00',
data: [<?php echo $unique; ?>],
borderWidth: 1
},
{
label: 'Bounced',
backgroundColor: '#ad1457',
borderColor: '#ad1457',
data: [<?php echo $bounced; ?>],
borderWidth: 1
},
]
},
options: {}
}
);
</script>
<?php
}
}
$message .= ' ' . $m . ' - ' . $response[ $m ]['message'];
}
} else {
$message = $response[ $this->method ]['message'];
}
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $message );
} else {
$values = array();
$labels = array();
$bounced = array();
$unique = array();
$count = 0;
$unique_sum = 0;
if ( is_array( $response['VisitsSummary.getVisits'] ) ) {
foreach ( $response['VisitsSummary.getVisits'] as $date => $value ) {
++$count;
$values [] = $value;
$unique [] = $response['VisitsSummary.getUniqueVisitors'][ $date ];
$bounced [] = $response['VisitsSummary.getBounceCount'][ $date ];
if ( 'week' === $this->parameter['period'] ) {
preg_match( '/[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/', $date, $date_list );
$text_key = $this->date_format( $date_list[0], 'short_week' );
} else {
$text_key = substr( $date, -2 );
}
$labels [] = array( $text_key );
$unique_sum += $response['VisitsSummary.getActions'][ $date ];
}
} else {
$values = array( 0 );
$labels = array( array( 0, '-' ) );
$unique = array( 0 );
$bounced = array( 0 );
}
$average = round( $unique_sum / 30, 0 );
?>
<div>
<canvas id="wp-piwik_stats_vistors_graph" style="height:220px;"></canvas>
</div>
<script>
new Chart(
document.getElementById('wp-piwik_stats_vistors_graph'),
{
type: 'line',
data: {
labels: <?php echo wp_json_encode( $labels ); ?>,
datasets: [
{
label: 'Visitors',
backgroundColor: '#0277bd',
borderColor: '#0277bd',
data: <?php echo wp_json_encode( $values ); ?>,
borderWidth: 1
},
{
label: 'Unique',
backgroundColor: '#ff8f00',
borderColor: '#ff8f00',
data: <?php echo wp_json_encode( $unique ); ?>,
borderWidth: 1
},
{
label: 'Bounced',
backgroundColor: '#ad1457',
borderColor: '#ad1457',
data: <?php echo wp_json_encode( $bounced ); ?>,
borderWidth: 1
},
]
},
options: {}
}
);
</script>
<?php
}
}
} }

View File

@ -1,73 +1,83 @@
<?php <?php
namespace WP_Piwik\Widget; namespace WP_Piwik\Widget;
use WP_Piwik\Widget; use WP_Piwik\Widget;
class City extends Widget { class City extends Widget {
public $className = __CLASS__; public $class_name = __CLASS__;
protected function configure($prefix = '', $params = array()) { protected function configure( $prefix = '', $params = array() ) {
$timeSettings = $this->getTimeSettings(); $time_settings = $this->get_time_settings();
$this->parameter = array( $this->parameter = array(
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId), 'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
'period' => $timeSettings['period'], 'period' => $time_settings['period'],
'date' => $timeSettings['date'] 'date' => $time_settings['date'],
); );
$this->title = $prefix.__('Cities', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')'; $this->title = $prefix . __( 'Cities', 'wp-piwik' ) . ' (' . $time_settings['description'] . ')';
$this->method = 'UserCountry.getCity'; $this->method = 'UserCountry.getCity';
$this->context = 'normal'; $this->context = 'normal';
wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
wp_enqueue_script ( 'wp-piwik-chartjs', self::$wpPiwik->getPluginURL () . 'js/chartjs/chart.min.js', "3.4.1" );
wp_enqueue_style('wp-piwik', self::$wpPiwik->getPluginURL().'css/wp-piwik.css',array(),self::$wpPiwik->getPluginVersion());
}
public function show() {
$response = self::$wpPiwik->request($this->apiID[$this->method]);
$tableBody = array();
if (!empty($response['result']) && $response['result'] ='error')
echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
else {
$tableHead = array(__('City', 'wp-piwik'), __('Unique', 'wp-piwik'), __('Percent', 'wp-piwik'));
if (isset($response[0]['nb_uniq_visitors'])) $unique = 'nb_uniq_visitors';
else $unique = 'sum_daily_nb_uniq_visitors';
$count = 0;
$sum = 0;
$js = array();
$class = array();
if (is_array($response))
foreach ($response as $row) {
$count++;
$sum += isset($row[$unique])?$row[$unique]:0;
if ($count < $this->limit)
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
elseif (!isset($tableBody['Others'])) {
$tableBody['Others'] = array($row['label'], $row[$unique], 0);
$class['Others'] = 'wp-piwik-hideDetails';
$js['Others'] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
$class[$row['label']] = 'wp-piwik-hideDetails hidden';
$js[$row['label']] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
} else {
$tableBody['Others'][1] += $row[$unique];
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
$class[$row['label']] = 'wp-piwik-hideDetails hidden';
$js[$row['label']] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
}
}
if ($count > $this->limit)
$tableBody['Others'][0] = __('Others', 'wp-piwik');
elseif ($count == $this->limit) {
$class['Others'] = $js['Others'] = '';
}
foreach ($tableBody as $key => $row)
$tableBody[$key][2] = number_format($row[1]/$sum*100, 2).'%';
if (!empty($tableBody)) $this->pieChart($tableBody);
$this->table($tableHead, $tableBody, null, false, $js, $class);
}
}
$version = self::$wp_piwik->get_plugin_version();
wp_enqueue_script( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'js/wp-piwik.js', array(), $version, true );
wp_enqueue_script( 'wp-piwik-chartjs', self::$wp_piwik->get_plugin_url() . 'js/chartjs/chart.min.js', array(), $version, false );
wp_enqueue_style( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'css/wp-piwik.css', array(), $version );
} }
public function show() {
$response = self::$wp_piwik->request( $this->api_id[ $this->method ] );
$table_body = array();
if ( ! empty( $response['result'] ) && 'error' === $response['result'] ) {
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $response['message'] );
} else {
$table_head = array( __( 'City', 'wp-piwik' ), __( 'Unique', 'wp-piwik' ), __( 'Percent', 'wp-piwik' ) );
if ( isset( $response[0]['nb_uniq_visitors'] ) ) {
$unique = 'nb_uniq_visitors';
} else {
$unique = 'sum_daily_nb_uniq_visitors';
}
$count = 0;
$sum = 0;
$js = array();
$css_class = array();
if ( is_array( $response ) ) {
foreach ( $response as $row ) {
++$count;
$sum += isset( $row[ $unique ] ) ? $row[ $unique ] : 0;
if ( $count < $this->limit ) {
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
} elseif ( ! isset( $table_body['Others'] ) ) {
$table_body['Others'] = array( $row['label'], $row[ $unique ], 0 );
$css_class['Others'] = 'wp-piwik-hideDetails';
$js['Others'] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
$css_class[ $row['label'] ] = 'wp-piwik-hideDetails hidden';
$js[ $row['label'] ] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
} else {
$table_body['Others'][1] += $row[ $unique ];
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
$css_class[ $row['label'] ] = 'wp-piwik-hideDetails hidden';
$js[ $row['label'] ] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
}
}
}
if ( $count > $this->limit ) {
$table_body['Others'][0] = __( 'Others', 'wp-piwik' );
} elseif ( $count === $this->limit ) {
$css_class['Others'] = '';
$js['Others'] = '';
}
foreach ( $table_body as $key => $row ) {
$table_body[ $key ][2] = number_format( $row[1] / $sum * 100, 2 ) . '%';
}
if ( ! empty( $table_body ) ) {
$this->pie_chart( $table_body );
}
$this->table( $table_head, $table_body, null, false, $js, $css_class );
}
}
}

View File

@ -4,70 +4,80 @@
use WP_Piwik\Widget; use WP_Piwik\Widget;
class Country extends Widget { class Country extends Widget {
public $className = __CLASS__; public $class_name = __CLASS__;
protected function configure($prefix = '', $params = array()) { protected function configure( $prefix = '', $params = array() ) {
$timeSettings = $this->getTimeSettings(); $time_settings = $this->get_time_settings();
$this->parameter = array( $this->parameter = array(
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId), 'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
'period' => $timeSettings['period'], 'period' => $time_settings['period'],
'date' => $timeSettings['date'] 'date' => $time_settings['date'],
); );
$this->title = $prefix.__('Countries', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')'; $this->title = $prefix . __( 'Countries', 'wp-piwik' ) . ' (' . $time_settings['description'] . ')';
$this->method = 'UserCountry.getCountry '; $this->method = 'UserCountry.getCountry ';
$this->context = 'normal'; $this->context = 'normal';
wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
wp_enqueue_script ( 'wp-piwik-chartjs', self::$wpPiwik->getPluginURL () . 'js/chartjs/chart.min.js', "3.4.1" );
wp_enqueue_style('wp-piwik', self::$wpPiwik->getPluginURL().'css/wp-piwik.css',array(),self::$wpPiwik->getPluginVersion());
}
public function show() {
$response = self::$wpPiwik->request($this->apiID[$this->method]);
$tableBody = array();
if (!empty($response['result']) && $response['result'] ='error')
echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
else {
$tableHead = array(__('Country', 'wp-piwik'), __('Unique', 'wp-piwik'), __('Percent', 'wp-piwik'));
if (isset($response[0]['nb_uniq_visitors'])) $unique = 'nb_uniq_visitors';
else $unique = 'sum_daily_nb_uniq_visitors';
$count = 0;
$sum = 0;
$js = array();
$class = array();
if (is_array($response))
foreach ($response as $row) {
$count++;
$sum += isset($row[$unique])?$row[$unique]:0;
if ($count < $this->limit)
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
elseif (!isset($tableBody['Others'])) {
$tableBody['Others'] = array($row['label'], $row[$unique], 0);
$class['Others'] = 'wp-piwik-hideDetails';
$js['Others'] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
$class[$row['label']] = 'wp-piwik-hideDetails hidden';
$js[$row['label']] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
} else {
$tableBody['Others'][1] += $row[$unique];
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
$class[$row['label']] = 'wp-piwik-hideDetails hidden';
$js[$row['label']] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
}
}
if ($count > $this->limit)
$tableBody['Others'][0] = __('Others', 'wp-piwik');
elseif ($count == $this->limit) {
$class['Others'] = $js['Others'] = '';
}
foreach ($tableBody as $key => $row)
$tableBody[$key][2] = number_format($row[1]/$sum*100, 2).'%';
if (!empty($tableBody)) $this->pieChart($tableBody);
$this->table($tableHead, $tableBody, null, false, $js, $class);
}
}
$version = self::$wp_piwik->get_plugin_version();
wp_enqueue_script( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'js/wp-piwik.js', array(), $version, true );
wp_enqueue_script( 'wp-piwik-chartjs', self::$wp_piwik->get_plugin_url() . 'js/chartjs/chart.min.js', array(), $version, false );
wp_enqueue_style( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'css/wp-piwik.css', array(), $version );
} }
public function show() {
$response = self::$wp_piwik->request( $this->api_id[ $this->method ] );
$table_body = array();
if ( ! empty( $response['result'] ) && 'error' === $response['result'] ) {
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $response['message'] );
} else {
$table_head = array( __( 'Country', 'wp-piwik' ), __( 'Unique', 'wp-piwik' ), __( 'Percent', 'wp-piwik' ) );
if ( isset( $response[0]['nb_uniq_visitors'] ) ) {
$unique = 'nb_uniq_visitors';
} else {
$unique = 'sum_daily_nb_uniq_visitors';
}
$count = 0;
$sum = 0;
$js = array();
$css_class = array();
if ( is_array( $response ) ) {
foreach ( $response as $row ) {
++$count;
$sum += isset( $row[ $unique ] ) ? $row[ $unique ] : 0;
if ( $count < $this->limit ) {
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
} elseif ( ! isset( $table_body['Others'] ) ) {
$table_body['Others'] = array( $row['label'], $row[ $unique ], 0 );
$css_class['Others'] = 'wp-piwik-hideDetails';
$js['Others'] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
$css_class[ $row['label'] ] = 'wp-piwik-hideDetails hidden';
$js[ $row['label'] ] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
} else {
$table_body['Others'][1] += $row[ $unique ];
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
$css_class[ $row['label'] ] = 'wp-piwik-hideDetails hidden';
$js[ $row['label'] ] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
}
}
}
if ( $count > $this->limit ) {
$table_body['Others'][0] = __( 'Others', 'wp-piwik' );
} elseif ( $count === $this->limit ) {
$css_class['Others'] = '';
$js['Others'] = '';
}
foreach ( $table_body as $key => $row ) {
$table_body[ $key ][2] = number_format( $row[1] / $sum * 100, 2 ) . '%';
}
if ( ! empty( $table_body ) ) {
$this->pie_chart( $table_body );
}
$this->table( $table_head, $table_body, null, false, $js, $css_class );
}
}
}

View File

@ -2,50 +2,52 @@
namespace WP_Piwik\Widget; namespace WP_Piwik\Widget;
class Ecommerce extends \WP_Piwik\Widget class Ecommerce extends \WP_Piwik\Widget {
{
public $className = __CLASS__;
protected function configure($prefix = '', $params = array()) public $class_name = __CLASS__;
{
$timeSettings = $this->getTimeSettings();
$this->title = $prefix . __('E-Commerce', 'wp-piwik');
$this->method = 'Goals.get';
$this->parameter = array(
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId),
'period' => $timeSettings['period'],
'date' => $timeSettings['date']
);
}
public function show() protected function configure( $prefix = '', $params = array() ) {
{ $time_settings = $this->get_time_settings();
$response = self::$wpPiwik->request($this->apiID[$this->method]); $this->title = $prefix . __( 'E-Commerce', 'wp-piwik' );
if (!empty($response['result']) && $response['result'] = 'error') $this->method = 'Goals.get';
echo '<strong>' . __('Piwik error', 'wp-piwik') . ':</strong> ' . htmlentities($response['message'], ENT_QUOTES, 'utf-8'); $this->parameter = array(
else { 'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
$tableHead = null; 'period' => $time_settings['period'],
$revenue = is_float($this->value($response, 'revenue')) ? number_format($this->value($response, 'revenue'), 2) : ""; 'date' => $time_settings['date'],
$revenue_new = is_float($this->value($response, 'revenue_new_visit')) ? number_format($this->value($response, 'revenue_new_visit'), 2) : ""; );
$revenue_return = is_float($this->value($response, 'revenue_returning_visit')) ? number_format($this->value($response, 'revenue_returning_visit'), 2) : ""; }
$tableBody = array(
array(__('Conversions', 'wp-piwik') . ':', $this->value($response, 'nb_conversions')),
array(__('Visits converted', 'wp-piwik') . ':', $this->value($response, 'nb_visits_converted')),
array(__('Revenue', 'wp-piwik') . ':', $revenue),
array(__('Conversion rate', 'wp-piwik') . ':', $this->value($response, 'conversion_rate')),
array(__('Conversions (new visitor)', 'wp-piwik') . ':', $this->value($response, 'nb_conversions_new_visit')),
array(__('Visits converted (new visitor)', 'wp-piwik') . ':', $this->value($response, 'nb_visits_converted_new_visit')),
array(__('Revenue (new visitor)', 'wp-piwik') . ':', $revenue_new),
array(__('Conversion rate (new visitor)', 'wp-piwik') . ':', $this->value($response, 'conversion_rate_new_visit')),
array(__('Conversions (returning visitor)', 'wp-piwik') . ':', $this->value($response, 'nb_conversions_returning_visit')),
array(__('Visits converted (returning visitor)', 'wp-piwik') . ':', $this->value($response, 'nb_visits_converted_returning_visit')),
array(__('Revenue (returning visitor)', 'wp-piwik') . ':', $revenue_return),
array(__('Conversion rate (returning visitor)', 'wp-piwik') . ':', $this->value($response, 'conversion_rate_returning_visit')),
);
$tableFoot = (self::$settings->getGlobalOption('piwik_shortcut') ? array(__('Shortcut', 'wp-piwik') . ':', '<a href="' . self::$settings->getGlobalOption('piwik_url') . '">Piwik</a>' . (isset($aryConf['inline']) && $aryConf['inline'] ? ' - <a href="?page=wp-piwik_stats">WP-Piwik</a>' : '')) : null);
$this->table($tableHead, $tableBody, $tableFoot);
}
}
public function show() {
$response = self::$wp_piwik->request( $this->api_id[ $this->method ] );
if ( ! empty( $response['result'] ) && 'error' === $response['result'] ) {
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $response['message'] );
} else {
$table_head = null;
$revenue = is_numeric( $this->value( $response, 'revenue' ) ) ? number_format( (float) $this->value( $response, 'revenue' ), 2 ) : '';
$revenue_new = is_numeric( $this->value( $response, 'revenue_new_visit' ) ) ? number_format( (float) $this->value( $response, 'revenue_new_visit' ), 2 ) : '';
$revenue_return = is_numeric( $this->value( $response, 'revenue_returning_visit' ) ) ? number_format( (float) $this->value( $response, 'revenue_returning_visit' ), 2 ) : '';
$table_body = array(
array( __( 'Conversions', 'wp-piwik' ) . ':', $this->value( $response, 'nb_conversions' ) ),
array( __( 'Visits converted', 'wp-piwik' ) . ':', $this->value( $response, 'nb_visits_converted' ) ),
array( __( 'Revenue', 'wp-piwik' ) . ':', $revenue ),
array( __( 'Conversion rate', 'wp-piwik' ) . ':', $this->value( $response, 'conversion_rate' ) ),
array( __( 'Conversions (new visitor)', 'wp-piwik' ) . ':', $this->value( $response, 'nb_conversions_new_visit' ) ),
array( __( 'Visits converted (new visitor)', 'wp-piwik' ) . ':', $this->value( $response, 'nb_visits_converted_new_visit' ) ),
array( __( 'Revenue (new visitor)', 'wp-piwik' ) . ':', $revenue_new ),
array( __( 'Conversion rate (new visitor)', 'wp-piwik' ) . ':', $this->value( $response, 'conversion_rate_new_visit' ) ),
array( __( 'Conversions (returning visitor)', 'wp-piwik' ) . ':', $this->value( $response, 'nb_conversions_returning_visit' ) ),
array( __( 'Visits converted (returning visitor)', 'wp-piwik' ) . ':', $this->value( $response, 'nb_visits_converted_returning_visit' ) ),
array( __( 'Revenue (returning visitor)', 'wp-piwik' ) . ':', $revenue_return ),
array( __( 'Conversion rate (returning visitor)', 'wp-piwik' ) . ':', $this->value( $response, 'conversion_rate_returning_visit' ) ),
);
$table_foot = self::$settings->get_global_option( 'piwik_shortcut' )
? array(
esc_html__( 'Shortcut', 'wp-piwik' ) . ':',
'<a href="' . esc_attr( self::$settings->get_global_option( 'piwik_url' ) ) . '">Piwik</a>',
)
: null;
$this->table( $table_head, $table_body, $table_foot );
}
}
} }

View File

@ -1,52 +1,55 @@
<?php <?php
namespace WP_Piwik\Widget; namespace WP_Piwik\Widget;
class Items extends \WP_Piwik\Widget { class Items extends \WP_Piwik\Widget {
public $className = __CLASS__; public $class_name = __CLASS__;
protected function configure($prefix = '', $params = array()) {
$timeSettings = $this->getTimeSettings();
$this->title = $prefix.__('E-Commerce Items', 'wp-piwik');
$this->method = 'Goals.getItemsName';
$this->parameter = array(
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId),
'period' => $timeSettings['period'],
'date' => $timeSettings['date']
);
}
public function show() {
$response = self::$wpPiwik->request($this->apiID[$this->method]);
if (!empty($response['result']) && $response['result'] ='error')
echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
else {
$tableHead = array(
__('Label', 'wp-piwik'),
__('Revenue', 'wp-piwik'),
__('Quantity', 'wp-piwik'),
__('Orders', 'wp-piwik'),
__('Avg. price', 'wp-piwik'),
__('Avg. quantity', 'wp-piwik'),
__('Conversion rate', 'wp-piwik'),
);
$tableBody = array();
if (is_array($response))
foreach ($response as $data) {
array_push($tableBody, array(
$data['label'],
number_format($data['revenue'],2),
$data['quantity'],
$data['orders'],
number_format($data['avg_price'],2),
$data['avg_quantity'],
$data['conversion_rate']
));
}
$tableFoot = array();
$this->table($tableHead, $tableBody, $tableFoot);
}
}
protected function configure( $prefix = '', $params = array() ) {
$time_settings = $this->get_time_settings();
$this->title = $prefix . __( 'E-Commerce Items', 'wp-piwik' );
$this->method = 'Goals.getItemsName';
$this->parameter = array(
'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
'period' => $time_settings['period'],
'date' => $time_settings['date'],
);
} }
public function show() {
$response = self::$wp_piwik->request( $this->api_id[ $this->method ] );
if ( ! empty( $response['result'] ) && 'error' === $response['result'] ) {
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $response['message'] );
} else {
$table_head = array(
__( 'Label', 'wp-piwik' ),
__( 'Revenue', 'wp-piwik' ),
__( 'Quantity', 'wp-piwik' ),
__( 'Orders', 'wp-piwik' ),
__( 'Avg. price', 'wp-piwik' ),
__( 'Avg. quantity', 'wp-piwik' ),
__( 'Conversion rate', 'wp-piwik' ),
);
$table_body = array();
if ( is_array( $response ) ) {
foreach ( $response as $data ) {
array_push(
$table_body,
array(
$data['label'],
number_format( $data['revenue'], 2 ),
$data['quantity'],
$data['orders'],
number_format( $data['avg_price'], 2 ),
$data['avg_quantity'],
$data['conversion_rate'],
)
);
}
}
$table_foot = array();
$this->table( $table_head, $table_body, $table_foot );
}
}
}

View File

@ -4,49 +4,52 @@ namespace WP_Piwik\Widget;
class ItemsCategory extends \WP_Piwik\Widget { class ItemsCategory extends \WP_Piwik\Widget {
public $className = __CLASS__; public $class_name = __CLASS__;
protected function configure($prefix = '', $params = array()) { protected function configure( $prefix = '', $params = array() ) {
$timeSettings = $this->getTimeSettings(); $time_settings = $this->get_time_settings();
$this->title = $prefix.__('E-Commerce Item Categories', 'wp-piwik'); $this->title = $prefix . __( 'E-Commerce Item Categories', 'wp-piwik' );
$this->method = 'Goals.getItemsCategory'; $this->method = 'Goals.getItemsCategory';
$this->parameter = array( $this->parameter = array(
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId), 'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
'period' => $timeSettings['period'], 'period' => $time_settings['period'],
'date' => $timeSettings['date'] 'date' => $time_settings['date'],
); );
} }
public function show() {
$response = self::$wpPiwik->request($this->apiID[$this->method]);
if (!empty($response['result']) && $response['result'] ='error')
echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
else {
$tableHead = array(
__('Label', 'wp-piwik'),
__('Revenue', 'wp-piwik'),
__('Quantity', 'wp-piwik'),
__('Orders', 'wp-piwik'),
__('Avg. price', 'wp-piwik'),
__('Avg. quantity', 'wp-piwik'),
__('Conversion rate', 'wp-piwik'),
);
$tableBody = array();
if (is_array($response))
foreach ($response as $data) {
array_push($tableBody, array(
$data['label'],
isset($data['revenue'])?number_format($data['revenue'],2):"-.--",
isset($data['quantity'])?$data['quantity']:'-',
isset($data['orders'])?$data['orders']:'-',
number_format($data['avg_price'],2),
$data['avg_quantity'],
$data['conversion_rate']
));
}
$tableFoot = array();
$this->table($tableHead, $tableBody, $tableFoot);
}
}
public function show() {
$response = self::$wp_piwik->request( $this->api_id[ $this->method ] );
if ( ! empty( $response['result'] ) && 'error' === $response['result'] ) {
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $response['message'] );
} else {
$table_head = array(
__( 'Label', 'wp-piwik' ),
__( 'Revenue', 'wp-piwik' ),
__( 'Quantity', 'wp-piwik' ),
__( 'Orders', 'wp-piwik' ),
__( 'Avg. price', 'wp-piwik' ),
__( 'Avg. quantity', 'wp-piwik' ),
__( 'Conversion rate', 'wp-piwik' ),
);
$table_body = array();
if ( is_array( $response ) ) {
foreach ( $response as $data ) {
array_push(
$table_body,
array(
$data['label'],
isset( $data['revenue'] ) ? number_format( $data['revenue'], 2 ) : '-.--',
isset( $data['quantity'] ) ? $data['quantity'] : '-',
isset( $data['orders'] ) ? $data['orders'] : '-',
number_format( $data['avg_price'], 2 ),
$data['avg_quantity'],
$data['conversion_rate'],
)
);
}
}
$table_foot = array();
$this->table( $table_head, $table_body, $table_foot );
}
}
} }

View File

@ -1,21 +1,20 @@
<?php <?php
namespace WP_Piwik\Widget; namespace WP_Piwik\Widget;
class Keywords extends \WP_Piwik\Widget { class Keywords extends \WP_Piwik\Widget {
public $className = __CLASS__; public $class_name = __CLASS__;
protected function configure($prefix = '', $params = array()) {
$timeSettings = $this->getTimeSettings();
$this->parameter = array(
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId),
'period' => $timeSettings['period'],
'date' => $timeSettings['date']
);
$this->title = $prefix.__('Keywords', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')';
$this->method = 'Referrers.getKeywords';
$this->name = 'Keyword';
}
protected function configure( $prefix = '', $params = array() ) {
$time_settings = $this->get_time_settings();
$this->parameter = array(
'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
'period' => $time_settings['period'],
'date' => $time_settings['date'],
);
$this->title = $prefix . __( 'Keywords', 'wp-piwik' ) . ' (' . $time_settings['description'] . ')';
$this->method = 'Referrers.getKeywords';
$this->name = 'Keyword';
} }
}

View File

@ -1,73 +1,83 @@
<?php <?php
namespace WP_Piwik\Widget; namespace WP_Piwik\Widget;
use WP_Piwik\Widget; use WP_Piwik\Widget;
class Models extends Widget { class Models extends Widget {
public $className = __CLASS__; public $class_name = __CLASS__;
protected function configure($prefix = '', $params = array()) { protected function configure( $prefix = '', $params = array() ) {
$timeSettings = $this->getTimeSettings(); $time_settings = $this->get_time_settings();
$this->parameter = array( $this->parameter = array(
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId), 'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
'period' => $timeSettings['period'], 'period' => $time_settings['period'],
'date' => $timeSettings['date'] 'date' => $time_settings['date'],
); );
$this->title = $prefix.__('Models', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')'; $this->title = $prefix . __( 'Models', 'wp-piwik' ) . ' (' . $time_settings['description'] . ')';
$this->method = 'DevicesDetection.getModel'; $this->method = 'DevicesDetection.getModel';
$this->context = 'normal'; $this->context = 'normal';
wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
wp_enqueue_script ( 'wp-piwik-chartjs', self::$wpPiwik->getPluginURL () . 'js/chartjs/chart.min.js', "3.4.1" );
wp_enqueue_style('wp-piwik', self::$wpPiwik->getPluginURL().'css/wp-piwik.css',array(),self::$wpPiwik->getPluginVersion());
}
public function show() {
$response = self::$wpPiwik->request($this->apiID[$this->method]);
$tableBody = array();
if (!empty($response['result']) && $response['result'] ='error')
echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
else {
$tableHead = array(__('Model', 'wp-piwik'), __('Unique', 'wp-piwik'), __('Percent', 'wp-piwik'));
if (isset($response[0]['nb_uniq_visitors'])) $unique = 'nb_uniq_visitors';
else $unique = 'sum_daily_nb_uniq_visitors';
$count = 0;
$sum = 0;
$js = array();
$class = array();
if (is_array($response))
foreach ($response as $row) {
$count++;
$sum += isset($row[$unique])?$row[$unique]:0;
if ($count < $this->limit)
$tableBody[$row['label']] = array(htmlentities($row['label']), $row[$unique], 0);
elseif (!isset($tableBody['Others'])) {
$tableBody['Others'] = array($row['label'], $row[$unique], 0);
$class['Others'] = 'wp-piwik-hideDetails';
$js['Others'] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
$class[$row['label']] = 'wp-piwik-hideDetails hidden';
$js[$row['label']] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
} else {
$tableBody['Others'][1] += $row[$unique];
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
$class[$row['label']] = 'wp-piwik-hideDetails hidden';
$js[$row['label']] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
}
}
if ($count > $this->limit)
$tableBody['Others'][0] = __('Others', 'wp-piwik');
elseif ($count == $this->limit) {
$class['Others'] = $js['Others'] = '';
}
foreach ($tableBody as $key => $row)
$tableBody[$key][2] = number_format($row[1]/$sum*100, 2).'%';
if (!empty($tableBody)) $this->pieChart($tableBody);
$this->table($tableHead, $tableBody, null, false, $js, $class);
}
}
$version = self::$wp_piwik->get_plugin_version();
wp_enqueue_script( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'js/wp-piwik.js', array(), $version, true );
wp_enqueue_script( 'wp-piwik-chartjs', self::$wp_piwik->get_plugin_url() . 'js/chartjs/chart.min.js', array(), $version, false );
wp_enqueue_style( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'css/wp-piwik.css', array(), $version );
} }
public function show() {
$response = self::$wp_piwik->request( $this->api_id[ $this->method ] );
$table_body = array();
if ( ! empty( $response['result'] ) && 'error' === $response['result'] ) {
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $response['message'] );
} else {
$table_head = array( __( 'Model', 'wp-piwik' ), __( 'Unique', 'wp-piwik' ), __( 'Percent', 'wp-piwik' ) );
if ( isset( $response[0]['nb_uniq_visitors'] ) ) {
$unique = 'nb_uniq_visitors';
} else {
$unique = 'sum_daily_nb_uniq_visitors';
}
$count = 0;
$sum = 0;
$js = array();
$css_class = array();
if ( is_array( $response ) ) {
foreach ( $response as $row ) {
++$count;
$sum += isset( $row[ $unique ] ) ? $row[ $unique ] : 0;
if ( $count < $this->limit ) {
$table_body[ $row['label'] ] = array( htmlentities( $row['label'] ), $row[ $unique ], 0 );
} elseif ( ! isset( $table_body['Others'] ) ) {
$table_body['Others'] = array( $row['label'], $row[ $unique ], 0 );
$css_class['Others'] = 'wp-piwik-hideDetails';
$js['Others'] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
$css_class[ $row['label'] ] = 'wp-piwik-hideDetails hidden';
$js[ $row['label'] ] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
} else {
$table_body['Others'][1] += $row[ $unique ];
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
$css_class[ $row['label'] ] = 'wp-piwik-hideDetails hidden';
$js[ $row['label'] ] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
}
}
}
if ( $count > $this->limit ) {
$table_body['Others'][0] = __( 'Others', 'wp-piwik' );
} elseif ( $count === $this->limit ) {
$css_class['Others'] = '';
$js['Others'] = '';
}
foreach ( $table_body as $key => $row ) {
$table_body[ $key ][2] = number_format( $row[1] / $sum * 100, 2 ) . '%';
}
if ( ! empty( $table_body ) ) {
$this->pie_chart( $table_body );
}
$this->table( $table_head, $table_body, null, false, $js, $css_class );
}
}
}

View File

@ -2,37 +2,42 @@
namespace WP_Piwik\Widget; namespace WP_Piwik\Widget;
class Noresult extends \WP_Piwik\Widget { class Noresult extends \WP_Piwik\Widget {
public $className = __CLASS__; public $class_name = __CLASS__;
protected function configure($prefix = '', $params = array()) {
$timeSettings = $this->getTimeSettings();
$this->parameter = array(
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId),
'period' => $timeSettings['period'],
'date' => $timeSettings['date']
);
$this->title = $prefix.__('Site Search', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')';
$this->method = 'Actions.getSiteSearchNoResultKeywords';
}
public function show() {
$response = self::$wpPiwik->request($this->apiID[$this->method]);
if (!empty($response['result']) && $response['result'] ='error')
echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
else {
$tableHead = array(__('Keyword', 'wp-piwik'), __('Requests', 'wp-piwik'), __('Bounced', 'wp-piwik'));
$tableBody = array();
$count = 0;
if (is_array($response))
foreach ($response as $row) {
$count++;
$tableBody[] = array($row['label'], $row['nb_visits'], $row['bounce_rate']);
if ($count == 10) break;
}
$this->table($tableHead, $tableBody, null);
}
}
protected function configure( $prefix = '', $params = array() ) {
$time_settings = $this->get_time_settings();
$this->parameter = array(
'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
'period' => $time_settings['period'],
'date' => $time_settings['date'],
);
$this->title = $prefix . __( 'Site Search', 'wp-piwik' ) . ' (' . $time_settings['description'] . ')';
$this->method = 'Actions.getSiteSearchNoResultKeywords';
} }
public function show() {
$response = self::$wp_piwik->request( $this->api_id[ $this->method ] );
if (
! empty( $response['result'] )
&& 'error' === $response['result']
) {
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $response['message'] );
} else {
$table_head = array( __( 'Keyword', 'wp-piwik' ), __( 'Requests', 'wp-piwik' ), __( 'Bounced', 'wp-piwik' ) );
$table_body = array();
$count = 0;
if ( is_array( $response ) ) {
foreach ( $response as $row ) {
++$count;
$table_body[] = array( $row['label'], $row['nb_visits'], $row['bounce_rate'] );
if ( 10 === $count ) {
break;
}
}
}
$this->table( $table_head, $table_body, null );
}
}
}

View File

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

View File

@ -2,65 +2,76 @@
namespace WP_Piwik\Widget; namespace WP_Piwik\Widget;
class Overview extends \WP_Piwik\Widget class Overview extends \WP_Piwik\Widget {
{
public $className = __CLASS__; public $class_name = __CLASS__;
protected function configure($prefix = '', $params = array()) protected function configure( $prefix = '', $params = array() ) {
{ $time_settings = $this->get_time_settings();
$timeSettings = $this->getTimeSettings(); $this->parameter = array(
$this->parameter = array( 'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId), 'period' => isset( $params['period'] ) ? $params['period'] : $time_settings['period'],
'period' => isset($params['period']) ? $params['period'] : $timeSettings['period'], 'date' => isset( $params['date'] ) ? $params['date'] : $time_settings['date'],
'date' => isset($params['date']) ? $params['date'] : $timeSettings['date'], 'description' => $time_settings['description'],
'description' => $timeSettings['description'] );
); $this->title = ! $this->is_shortcode ? $prefix . __( 'Overview', 'wp-piwik' ) . ' (' . ( 'dashboard' === $this->page_id ? $this->range_name() : $time_settings['description'] ) . ')' : ( $params['title'] ? $params['title'] : '' );
$this->title = !$this->isShortcode ? $prefix . __('Overview', 'wp-piwik') . ' (' . __($this->pageId == 'dashboard' ? $this->rangeName() : $timeSettings['description'], 'wp-piwik') . ')' : ($params['title'] ? $params['title'] : ''); $this->method = 'VisitsSummary.get';
$this->method = 'VisitsSummary.get'; }
}
public function show()
{
$response = self::$wpPiwik->request($this->apiID[$this->method]);
if (!empty($response['result']) && $response['result'] = 'error')
echo '<strong>' . __('Piwik error', 'wp-piwik') . ':</strong> ' . htmlentities($response['message'], ENT_QUOTES, 'utf-8');
else {
if (in_array($this->parameter['date'], array('last30', 'last60', 'last90'))) {
$result = array();
if (is_array($response)) {
foreach ($response as $data)
foreach ($data as $key => $value)
if (isset($result[$key]) && is_numeric($value))
$result[$key] += $value;
elseif (is_numeric($value))
$result[$key] = $value;
else
$result[$key] = 0;
if (isset($result['nb_visits']) && $result['nb_visits'] > 0) {
$result['nb_actions_per_visit'] = round($result['nb_actions'] / $result['nb_visits'], 1);
$result['bounce_rate'] = round($result['bounce_count'] / $result['nb_visits'] * 100, 1) . '%';
$result['avg_time_on_site'] = round($result['sum_visit_length'] / $result['nb_visits'], 0);
} else $result['nb_actions_per_visit'] = $result['bounce_rate'] = $result['avg_time_on_site'] = 0;
}
$response = $result;
}
$time = isset($response['sum_visit_length']) ? $this->timeFormat($response['sum_visit_length']) : '-';
$avgTime = isset($response['avg_time_on_site']) ? $this->timeFormat($response['avg_time_on_site']) : '-';
$tableHead = null;
$tableBody = array(array(__('Visitors', 'wp-piwik') . ':', $this->value($response, 'nb_visits')));
if ($this->value($response, 'nb_uniq_visitors') != '-')
array_push($tableBody, array(__('Unique visitors', 'wp-piwik') . ':', $this->value($response, 'nb_uniq_visitors')));
array_push($tableBody,
array(__('Page views', 'wp-piwik') . ':', $this->value($response, 'nb_actions') . ' (&#216; ' . $this->value($response, 'nb_actions_per_visit') . ')'),
array(__('Total time spent', 'wp-piwik') . ':', $time . ' (&#216; ' . $avgTime . ')'),
array(__('Bounce count', 'wp-piwik') . ':', $this->value($response, 'bounce_count') . ' (' . $this->value($response, 'bounce_rate') . ')')
);
if (!in_array($this->parameter['date'], array('last30', 'last60', 'last90')))
array_push($tableBody, array(__('Time/visit', 'wp-piwik') . ':', $avgTime), array(__('Max. page views in one visit', 'wp-piwik') . ':', $this->value($response, 'max_actions')));
$tableFoot = (self::$settings->getGlobalOption('piwik_shortcut') ? array(__('Shortcut', 'wp-piwik') . ':', '<a href="' . self::$settings->getGlobalOption('piwik_url') . '" target="_BLANK">Matomo</a>' . (isset($aryConf['inline']) && $aryConf['inline'] ? ' - <a href="?page=wp-piwik_stats">WP-Piwik</a>' : '')) : null);
$this->table($tableHead, $tableBody, $tableFoot);
}
}
public function show() {
$response = self::$wp_piwik->request( $this->api_id[ $this->method ] );
if ( ! empty( $response['result'] ) && 'error' === $response['result'] ) {
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $response['message'] );
} else {
if ( in_array( $this->parameter['date'], array( 'last30', 'last60', 'last90' ), true ) ) {
$result = array();
if ( is_array( $response ) ) {
foreach ( $response as $data ) {
foreach ( $data as $key => $value ) {
if ( isset( $result[ $key ] ) && is_numeric( $value ) ) {
$result[ $key ] += $value;
} elseif ( is_numeric( $value ) ) {
$result[ $key ] = $value;
} else {
$result[ $key ] = 0;
}
}
}
if ( isset( $result['nb_visits'] ) && $result['nb_visits'] > 0 ) {
$result['nb_actions_per_visit'] = round( $result['nb_actions'] / $result['nb_visits'], 1 );
$result['bounce_rate'] = round( $result['bounce_count'] / $result['nb_visits'] * 100, 1 ) . '%';
$result['avg_time_on_site'] = round( $result['sum_visit_length'] / $result['nb_visits'], 0 );
} else {
$result['nb_actions_per_visit'] = 0;
$result['bounce_rate'] = 0;
$result['avg_time_on_site'] = 0;
}
}
$response = $result;
}
$time = isset( $response['sum_visit_length'] ) ? $this->time_format( $response['sum_visit_length'] ) : '-';
$avg_time = isset( $response['avg_time_on_site'] ) ? $this->time_format( $response['avg_time_on_site'] ) : '-';
$table_head = null;
$table_body = array( array( __( 'Visitors', 'wp-piwik' ) . ':', $this->value( $response, 'nb_visits' ) ) );
if ( '-' !== $this->value( $response, 'nb_uniq_visitors' ) ) {
array_push( $table_body, array( __( 'Unique visitors', 'wp-piwik' ) . ':', $this->value( $response, 'nb_uniq_visitors' ) ) );
}
array_push(
$table_body,
array( __( 'Page views', 'wp-piwik' ) . ':', $this->value( $response, 'nb_actions' ) . ' (&#216; ' . $this->value( $response, 'nb_actions_per_visit' ) . ')' ),
array( __( 'Total time spent', 'wp-piwik' ) . ':', $time . ' (&#216; ' . $avg_time . ')' ),
array( __( 'Bounce count', 'wp-piwik' ) . ':', $this->value( $response, 'bounce_count' ) . ' (' . $this->value( $response, 'bounce_rate' ) . ')' )
);
if ( ! in_array( $this->parameter['date'], array( 'last30', 'last60', 'last90' ), true ) ) {
array_push( $table_body, array( __( 'Time/visit', 'wp-piwik' ) . ':', $avg_time ), array( __( 'Max. page views in one visit', 'wp-piwik' ) . ':', $this->value( $response, 'max_actions' ) ) );
}
$table_foot = self::$settings->get_global_option( 'piwik_shortcut' )
? array(
esc_html__( 'Shortcut', 'wp-piwik' ) . ':',
'<a href="' . esc_attr( self::$settings->get_global_option( 'piwik_url' ) ) . '" target="_BLANK">Matomo</a>',
)
: null;
$this->table( $table_head, $table_body, $table_foot );
}
}
} }

View File

@ -1,21 +1,20 @@
<?php <?php
namespace WP_Piwik\Widget; namespace WP_Piwik\Widget;
class Pages extends \WP_Piwik\Widget { class Pages extends \WP_Piwik\Widget {
public $className = __CLASS__; public $class_name = __CLASS__;
protected function configure($prefix = '', $params = array()) {
$timeSettings = $this->getTimeSettings();
$this->parameter = array(
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId),
'period' => $timeSettings['period'],
'date' => $timeSettings['date']
);
$this->title = $prefix.__('Pages', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')';
$this->method = 'Actions.getPageTitles';
$this->name = __('Page', 'wp-piwik' );
}
protected function configure( $prefix = '', $params = array() ) {
$time_settings = $this->get_time_settings();
$this->parameter = array(
'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
'period' => $time_settings['period'],
'date' => $time_settings['date'],
);
$this->title = $prefix . __( 'Pages', 'wp-piwik' ) . ' (' . $time_settings['description'] . ')';
$this->method = 'Actions.getPageTitles';
$this->name = __( 'Page', 'wp-piwik' );
} }
}

View File

@ -1,38 +1,40 @@
<?php <?php
namespace WP_Piwik\Widget; namespace WP_Piwik\Widget;
class Plugins extends \WP_Piwik\Widget { class Plugins extends \WP_Piwik\Widget {
public $className = __CLASS__; public $class_name = __CLASS__;
protected function configure($prefix = '', $params = array()) {
$timeSettings = $this->getTimeSettings();
$this->parameter = array(
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId),
'period' => $timeSettings['period'],
'date' => $timeSettings['date']
);
$this->title = $prefix.__('Plugins', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')';
$this->method = 'DevicePlugins.getPlugin';
}
public function show() {
$response = self::$wpPiwik->request($this->apiID[$this->method]);
if (!empty($response['result']) && $response['result'] ='error')
echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
else {
$tableHead = array(__('Plugin', 'wp-piwik'), __('Visits', 'wp-piwik'), __('Percent', 'wp-piwik'));
$tableBody = array();
$count = 0;
if (is_array($response))
foreach ($response as $row) {
$count++;
$tableBody[] = array($row['label'], $row['nb_visits'], $row['nb_visits_percentage']);
if ($count == 10) break;
}
$this->table($tableHead, $tableBody, null);
}
}
protected function configure( $prefix = '', $params = array() ) {
$time_settings = $this->get_time_settings();
$this->parameter = array(
'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
'period' => $time_settings['period'],
'date' => $time_settings['date'],
);
$this->title = $prefix . __( 'Plugins', 'wp-piwik' ) . ' (' . $time_settings['description'] . ')';
$this->method = 'DevicePlugins.getPlugin';
} }
public function show() {
$response = self::$wp_piwik->request( $this->api_id[ $this->method ] );
if ( ! empty( $response['result'] ) && 'error' === $response['result'] ) {
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $response['message'] );
} else {
$table_head = array( __( 'Plugin', 'wp-piwik' ), __( 'Visits', 'wp-piwik' ), __( 'Percent', 'wp-piwik' ) );
$table_body = array();
$count = 0;
if ( is_array( $response ) ) {
foreach ( $response as $row ) {
++$count;
$table_body[] = array( $row['label'], $row['nb_visits'], $row['nb_visits_percentage'] );
if ( 10 === $count ) {
break;
}
}
}
$this->table( $table_head, $table_body, null );
}
}
}

View File

@ -1,82 +1,95 @@
<?php <?php
namespace WP_Piwik\Widget; namespace WP_Piwik\Widget;
class Post extends \WP_Piwik\Widget { class Post extends \WP_Piwik\Widget {
public $className = __CLASS__; public $class_name = __CLASS__;
protected function configure($prefix = '', $params = array()) {
global $post;
$timeSettings = $this->getTimeSettings();
$this->parameter = array(
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId),
'period' => isset($params['period']) ? $params['period'] : $timeSettings['period'],
'date' => isset($params['date']) ? $params['date'] : $timeSettings['date'],
'key' => isset($params['key'])?$params['key']:null,
'pageUrl' => isset($params['url'])?$params['url']:urlencode(get_permalink($post->ID)),
'description' => $timeSettings['description']
);
$this->title = $prefix.__('Overview', 'wp-piwik').' ('.__($this->parameter['date'],'wp-piwik').')';
$this->method = 'Actions.getPageUrl';
}
public function show() {
$response = self::$wpPiwik->request($this->apiID[$this->method]);
if (!empty($response['result']) && $response['result'] = 'error')
echo '<strong>' . __('Piwik error', 'wp-piwik') . ':</strong> ' . htmlentities($response['message'], ENT_QUOTES, 'utf-8');
else {
if (in_array($this->parameter['date'], array('last30', 'last60', 'last90'))) {
$result = array();
if (is_array($response)) {
foreach ($response as $data) {
if (isset($data[0])) {
foreach ($data[0] as $key => $value)
if (isset($result[$key]) && is_numeric($value))
$result[$key] += $value;
elseif (is_numeric($value))
$result[$key] = $value;
else
$result[$key] = 0;
}
}
if (isset($result['nb_visits']) && $result['nb_visits'] > 0) {
$result['nb_actions_per_visit'] = round((isset( $result['nb_actions'] ) ? $result['nb_actions'] : 0) / $result['nb_visits'], 1);
$result['bounce_rate'] = round((isset($result['bounce_count']) ? $result['bounce_count'] : 0) / $result['nb_visits'] * 100, 1) . '%';
$result['avg_time_on_site'] = round((isset($result['sum_visit_length']) ? $result['sum_visit_length'] : 0) / $result['nb_visits'], 0);
} else $result['nb_actions_per_visit'] = $result['bounce_rate'] = $result['avg_time_on_site'] = 0;
}
$response = $result;
} else {
if (isset($response[0]))
$response = $response[0];
if ($this->parameter['key']) {
$this->out(isset($response[$this->parameter['key']])?$response[$this->parameter['key']]:'<em>not defined</em>');
return;
}
}
$time = isset($response['sum_visit_length']) ? $this->timeFormat($response['sum_visit_length']) : '-';
$avgTime = isset($response['avg_time_on_site']) ? $this->timeFormat($response['avg_time_on_site']) : '-';
$tableHead = null;
$tableBody = array(array(__('Visitors', 'wp-piwik') . ':', $this->value($response, 'nb_visits')));
if ($this->value($response, 'nb_uniq_visitors') != '-')
array_push($tableBody, array(__('Unique visitors', 'wp-piwik') . ':', $this->value($response, 'nb_uniq_visitors')));
elseif ($this->value($response, 'sum_daily_nb_uniq_visitors') != '-') {
array_push($tableBody, __('Unique visitors', 'wp-piwik') . ':', $this->value($response, 'sum_daily_nb_uniq_visitors'));
}
array_push($tableBody,
array(__('Page views', 'wp-piwik').':', $this->value($response, 'nb_hits').' (&#216; '.$this->value($response, 'entry_nb_actions').')'),
array(__('Total time spent', 'wp-piwik').':', $time),
array(__('Bounce count', 'wp-piwik').':', $this->value($response, 'entry_bounce_count').' ('.$this->value($response, 'bounce_rate').')'),
array(__('Time/visit', 'wp-piwik').':', $avgTime),
array(__('Min. generation time', 'wp-piwik').':', $this->value($response, 'min_time_generation')),
array(__('Max. generation time', 'wp-piwik').':', $this->value($response, 'max_time_generation'))
);
if (!in_array($this->parameter['date'], array('last30', 'last60', 'last90')))
array_push($tableBody, array(__('Time/visit', 'wp-piwik') . ':', $avgTime), array(__('Max. page views in one visit', 'wp-piwik') . ':', $this->value($response, 'max_actions')));
$tableFoot = (self::$settings->getGlobalOption('piwik_shortcut') ? array(__('Shortcut', 'wp-piwik') . ':', '<a href="' . self::$settings->getGlobalOption('piwik_url') . '">Piwik</a>' . (isset($aryConf['inline']) && $aryConf['inline'] ? ' - <a href="?page=wp-piwik_stats">WP-Piwik</a>' : '')) : null);
$this->table($tableHead, $tableBody, $tableFoot);
}
}
protected function configure( $prefix = '', $params = array() ) {
global $post;
$time_settings = $this->get_time_settings();
$this->parameter = array(
'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
'period' => isset( $params['period'] ) ? $params['period'] : $time_settings['period'],
'date' => isset( $params['date'] ) ? $params['date'] : $time_settings['date'],
'key' => isset( $params['key'] ) ? $params['key'] : null,
'pageUrl' => isset( $params['url'] ) ? $params['url'] : get_permalink( $post->ID ),
'description' => $time_settings['description'],
);
$this->title = $prefix . esc_html__( 'Overview', 'wp-piwik' ) . ' (' . $this->parameter['date'] . ')';
$this->method = 'Actions.getPageUrl';
} }
public function show() {
$response = self::$wp_piwik->request( $this->api_id[ $this->method ] );
if ( ! empty( $response['result'] ) && 'error' === $response['result'] ) {
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $response['message'] );
} else {
if ( in_array( $this->parameter['date'], array( 'last30', 'last60', 'last90' ), true ) ) {
$result = array();
if ( is_array( $response ) ) {
foreach ( $response as $data ) {
if ( isset( $data[0] ) ) {
foreach ( $data[0] as $key => $value ) {
if ( isset( $result[ $key ] ) && is_numeric( $value ) ) {
$result[ $key ] += $value;
} elseif ( is_numeric( $value ) ) {
$result[ $key ] = $value;
} else {
$result[ $key ] = 0;
}
}
}
}
if ( isset( $result['nb_visits'] ) && $result['nb_visits'] > 0 ) {
$result['nb_actions_per_visit'] = round( ( isset( $result['nb_actions'] ) ? $result['nb_actions'] : 0 ) / $result['nb_visits'], 1 );
$result['bounce_rate'] = round( ( isset( $result['bounce_count'] ) ? $result['bounce_count'] : 0 ) / $result['nb_visits'] * 100, 1 ) . '%';
$result['avg_time_on_site'] = round( ( isset( $result['sum_visit_length'] ) ? $result['sum_visit_length'] : 0 ) / $result['nb_visits'], 0 );
} else {
$result['nb_actions_per_visit'] = 0;
$result['bounce_rate'] = 0;
$result['avg_time_on_site'] = 0;
}
}
$response = $result;
} else {
if ( isset( $response[0] ) ) {
$response = $response[0];
}
if ( $this->parameter['key'] ) {
$this->out( isset( $response[ $this->parameter['key'] ] ) ? esc_html( $response[ $this->parameter['key'] ] ) : '<em>not defined</em>' );
return;
}
}
$time = isset( $response['sum_visit_length'] ) ? $this->time_format( $response['sum_visit_length'] ) : '-';
$avg_time = isset( $response['avg_time_on_site'] ) ? $this->time_format( $response['avg_time_on_site'] ) : '-';
$table_head = null;
$table_body = array( array( __( 'Visitors', 'wp-piwik' ) . ':', $this->value( $response, 'nb_visits' ) ) );
if ( '-' !== $this->value( $response, 'nb_uniq_visitors' ) ) {
array_push( $table_body, array( __( 'Unique visitors', 'wp-piwik' ) . ':', $this->value( $response, 'nb_uniq_visitors' ) ) );
} elseif ( '-' !== $this->value( $response, 'sum_daily_nb_uniq_visitors' ) ) {
array_push( $table_body, __( 'Unique visitors', 'wp-piwik' ) . ':', $this->value( $response, 'sum_daily_nb_uniq_visitors' ) );
}
array_push(
$table_body,
array( __( 'Page views', 'wp-piwik' ) . ':', $this->value( $response, 'nb_hits' ) . ' (&#216; ' . $this->value( $response, 'entry_nb_actions' ) . ')' ),
array( __( 'Total time spent', 'wp-piwik' ) . ':', $time ),
array( __( 'Bounce count', 'wp-piwik' ) . ':', $this->value( $response, 'entry_bounce_count' ) . ' (' . $this->value( $response, 'bounce_rate' ) . ')' ),
array( __( 'Time/visit', 'wp-piwik' ) . ':', $avg_time ),
array( __( 'Min. generation time', 'wp-piwik' ) . ':', $this->value( $response, 'min_time_generation' ) ),
array( __( 'Max. generation time', 'wp-piwik' ) . ':', $this->value( $response, 'max_time_generation' ) )
);
if ( ! in_array( $this->parameter['date'], array( 'last30', 'last60', 'last90' ), true ) ) {
array_push( $table_body, array( __( 'Time/visit', 'wp-piwik' ) . ':', $avg_time ), array( __( 'Max. page views in one visit', 'wp-piwik' ) . ':', $this->value( $response, 'max_actions' ) ) );
}
$table_foot = self::$settings->get_global_option( 'piwik_shortcut' )
? array(
esc_html__( 'Shortcut', 'wp-piwik' ) . ':',
'<a href="' . esc_attr( self::$settings->get_global_option( 'piwik_url' ) ) . '">Piwik</a>',
)
: null;
$this->table( $table_head, $table_body, $table_foot );
}
}
}

View File

@ -2,20 +2,19 @@
namespace WP_Piwik\Widget; namespace WP_Piwik\Widget;
class Referrers extends \WP_Piwik\Widget { class Referrers extends \WP_Piwik\Widget {
public $className = __CLASS__; public $class_name = __CLASS__;
protected function configure($prefix = '', $params = array()) {
$timeSettings = $this->getTimeSettings();
$this->parameter = array(
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId),
'period' => $timeSettings['period'],
'date' => $timeSettings['date']
);
$this->title = $prefix.__('Referrers', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')';
$this->method = 'Referrers.getWebsites';
$this->name = 'Referrer';
}
protected function configure( $prefix = '', $params = array() ) {
$time_settings = $this->get_time_settings();
$this->parameter = array(
'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
'period' => $time_settings['period'],
'date' => $time_settings['date'],
);
$this->title = $prefix . __( 'Referrers', 'wp-piwik' ) . ' (' . $time_settings['description'] . ')';
$this->method = 'Referrers.getWebsites';
$this->name = 'Referrer';
} }
}

View File

@ -1,68 +1,77 @@
<?php <?php
namespace WP_Piwik\Widget; namespace WP_Piwik\Widget;
class Screens extends \WP_Piwik\Widget { class Screens extends \WP_Piwik\Widget {
public $className = __CLASS__; public $class_name = __CLASS__;
protected function configure($prefix = '', $params = array()) { protected function configure( $prefix = '', $params = array() ) {
$timeSettings = $this->getTimeSettings(); $time_settings = $this->get_time_settings();
$this->parameter = array( $this->parameter = array(
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId), 'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
'period' => $timeSettings['period'], 'period' => $time_settings['period'],
'date' => $timeSettings['date'] 'date' => $time_settings['date'],
); );
$this->title = $prefix.__('Resolutions', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')'; $this->title = $prefix . __( 'Resolutions', 'wp-piwik' ) . ' (' . $time_settings['description'] . ')';
$this->method = 'Resolution.getResolution'; $this->method = 'Resolution.getResolution';
$this->context = 'normal'; $this->context = 'normal';
wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
wp_enqueue_script ( 'wp-piwik-chartjs', self::$wpPiwik->getPluginURL () . 'js/chartjs/chart.min.js', "3.4.1" );
wp_enqueue_style('wp-piwik', self::$wpPiwik->getPluginURL().'css/wp-piwik.css',array(),self::$wpPiwik->getPluginVersion());
}
public function show() {
$response = self::$wpPiwik->request($this->apiID[$this->method]);
$tableBody = array();
if (!empty($response['result']) && $response['result'] ='error')
echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
else {
$tableHead = array(__('Resolution', 'wp-piwik'), __('Unique', 'wp-piwik'), __('Percent', 'wp-piwik'));
if (isset($response[0]['nb_uniq_visitors'])) $unique = 'nb_uniq_visitors';
else $unique = 'sum_daily_nb_uniq_visitors';
$count = 0;
$sum = 0;
$js = array();
$class = array();
if (is_array($response))
foreach ($response as $row) {
$count++;
$sum += isset($row[$unique])?$row[$unique]:0;
if ($count < $this->limit)
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
elseif (!isset($tableBody['Others'])) {
$tableBody['Others'] = array($row['label'], $row[$unique], 0);
$class['Others'] = 'wp-piwik-hideDetails';
$js['Others'] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
$class[$row['label']] = 'wp-piwik-hideDetails hidden';
$js[$row['label']] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
} else {
$tableBody['Others'][1] += $row[$unique];
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
$class[$row['label']] = 'wp-piwik-hideDetails hidden';
$js[$row['label']] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
}
}
if ($count > $this->limit)
$tableBody['Others'][0] = __('Others', 'wp-piwik');
foreach ($tableBody as $key => $row)
$tableBody[$key][2] = number_format($row[1]/$sum*100, 2).'%';
if (!empty($tableBody)) $this->pieChart($tableBody);
$this->table($tableHead, $tableBody, null, false, $js, $class);
}
}
$version = self::$wp_piwik->get_plugin_version();
wp_enqueue_script( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'js/wp-piwik.js', array(), $version, true );
wp_enqueue_script( 'wp-piwik-chartjs', self::$wp_piwik->get_plugin_url() . 'js/chartjs/chart.min.js', array(), $version, false );
wp_enqueue_style( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'css/wp-piwik.css', array(), $version );
} }
public function show() {
$response = self::$wp_piwik->request( $this->api_id[ $this->method ] );
$table_body = array();
if ( ! empty( $response['result'] ) && 'error' === $response['result'] ) {
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $response['message'] );
} else {
$table_head = array( __( 'Resolution', 'wp-piwik' ), __( 'Unique', 'wp-piwik' ), __( 'Percent', 'wp-piwik' ) );
if ( isset( $response[0]['nb_uniq_visitors'] ) ) {
$unique = 'nb_uniq_visitors';
} else {
$unique = 'sum_daily_nb_uniq_visitors';
}
$count = 0;
$sum = 0;
$js = array();
$css_class = array();
if ( is_array( $response ) ) {
foreach ( $response as $row ) {
++$count;
$sum += isset( $row[ $unique ] ) ? $row[ $unique ] : 0;
if ( $count < $this->limit ) {
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
} elseif ( ! isset( $table_body['Others'] ) ) {
$table_body['Others'] = array( $row['label'], $row[ $unique ], 0 );
$css_class['Others'] = 'wp-piwik-hideDetails';
$js['Others'] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
$css_class[ $row['label'] ] = 'wp-piwik-hideDetails hidden';
$js[ $row['label'] ] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
} else {
$table_body['Others'][1] += $row[ $unique ];
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
$css_class[ $row['label'] ] = 'wp-piwik-hideDetails hidden';
$js[ $row['label'] ] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
}
}
}
if ( $count > $this->limit ) {
$table_body['Others'][0] = __( 'Others', 'wp-piwik' );
}
foreach ( $table_body as $key => $row ) {
$table_body[ $key ][2] = number_format( $row[1] / $sum * 100, 2 ) . '%';
}
if ( ! empty( $table_body ) ) {
$this->pie_chart( $table_body );
}
$this->table( $table_head, $table_body, null, false, $js, $css_class );
}
}
}

View File

@ -1,38 +1,40 @@
<?php <?php
namespace WP_Piwik\Widget; namespace WP_Piwik\Widget;
class Search extends \WP_Piwik\Widget { class Search extends \WP_Piwik\Widget {
public $className = __CLASS__; public $class_name = __CLASS__;
protected function configure($prefix = '', $params = array()) {
$timeSettings = $this->getTimeSettings();
$this->parameter = array(
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId),
'period' => $timeSettings['period'],
'date' => $timeSettings['date']
);
$this->title = $prefix.__('Site Search', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')';
$this->method = 'Actions.getSiteSearchKeywords';
}
public function show() {
$response = self::$wpPiwik->request($this->apiID[$this->method]);
if (!empty($response['result']) && $response['result'] ='error')
echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
else {
$tableHead = array(__('Keyword', 'wp-piwik'), __('Requests', 'wp-piwik'), __('Bounced', 'wp-piwik'));
$tableBody = array();
$count = 0;
if (is_array($response))
foreach ($response as $row) {
$count++;
$tableBody[] = array(htmlentities($row['label']), $row['nb_visits'], $row['bounce_rate']);
if ($count == 10) break;
}
$this->table($tableHead, $tableBody, null);
}
}
protected function configure( $prefix = '', $params = array() ) {
$time_settings = $this->get_time_settings();
$this->parameter = array(
'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
'period' => $time_settings['period'],
'date' => $time_settings['date'],
);
$this->title = $prefix . __( 'Site Search', 'wp-piwik' ) . ' (' . $time_settings['description'] . ')';
$this->method = 'Actions.getSiteSearchKeywords';
} }
public function show() {
$response = self::$wp_piwik->request( $this->api_id[ $this->method ] );
if ( ! empty( $response['result'] ) && 'error' === $response['result'] ) {
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $response['message'] );
} else {
$table_head = array( __( 'Keyword', 'wp-piwik' ), __( 'Requests', 'wp-piwik' ), __( 'Bounced', 'wp-piwik' ) );
$table_body = array();
$count = 0;
if ( is_array( $response ) ) {
foreach ( $response as $row ) {
++$count;
$table_body[] = array( $row['label'], $row['nb_visits'], $row['bounce_rate'] );
if ( 10 === $count ) {
break;
}
}
}
$this->table( $table_head, $table_body, null );
}
}
}

View File

@ -1,31 +1,33 @@
<?php <?php
namespace WP_Piwik\Widget; namespace WP_Piwik\Widget;
class Seo extends \WP_Piwik\Widget { class Seo extends \WP_Piwik\Widget {
public $className = __CLASS__; public $class_name = __CLASS__;
protected function configure($prefix = '', $params = array()) {
$this->parameter = array(
'url' => get_bloginfo('url')
);
$this->title = $prefix.__('SEO', 'wp-piwik');
$this->method = 'SEO.getRank';
}
public function show() {
$response = self::$wpPiwik->request($this->apiID[$this->method]);
if (!empty($response['result']) && $response['result'] ='error')
echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
else {
echo '<div class="table"><table class="widefat"><tbody>';
if (is_array($response))
foreach ($response as $val)
echo '<tr><td>'.(isset($val['logo_link']) && !empty($val['logo_link'])?'<a href="'.$val['logo_link'].'" title="'.$val['logo_tooltip'].'">'.$val['label'].'</a>':$val['label']).'</td><td>'.$val['rank'].'</td></tr>';
else echo '<tr><td>SEO module currently not available.</td></tr>';
echo '</tbody></table></div>';
}
}
protected function configure( $prefix = '', $params = array() ) {
$this->parameter = array(
'url' => get_bloginfo( 'url' ),
);
$this->title = $prefix . __( 'SEO', 'wp-piwik' );
$this->method = 'SEO.getRank';
} }
public function show() {
$response = self::$wp_piwik->request( $this->api_id[ $this->method ] );
if ( ! empty( $response['result'] ) && 'error' === $response['result'] ) {
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $response['message'] );
} else {
echo '<div class="table"><table class="widefat"><tbody>';
if ( is_array( $response ) ) {
foreach ( $response as $val ) {
echo '<tr><td>' . ( isset( $val['logo_link'] ) && ! empty( $val['logo_link'] ) ? '<a href="' . esc_attr( $val['logo_link'] ) . '" title="' . esc_attr( $val['logo_tooltip'] ) . '">' . esc_html( $val['label'] ) . '</a>' : esc_html( $val['label'] ) ) . '</td><td>' . esc_html( $val['rank'] ) . '</td></tr>';
}
} else {
echo '<tr><td>SEO module currently not available.</td></tr>';
}
echo '</tbody></table></div>';
}
}
}

View File

@ -1,66 +1,76 @@
<?php <?php
namespace WP_Piwik\Widget; namespace WP_Piwik\Widget;
class SystemDetails extends \WP_Piwik\Widget { class SystemDetails extends \WP_Piwik\Widget {
protected function configure($prefix = '', $params = array()) { protected function configure( $prefix = '', $params = array() ) {
$timeSettings = $this->getTimeSettings(); $time_settings = $this->get_time_settings();
$this->parameter = array( $this->parameter = array(
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId), 'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
'period' => $timeSettings['period'], 'period' => $time_settings['period'],
'date' => $timeSettings['date'] 'date' => $time_settings['date'],
); );
$this->title = $prefix.__('Operation System Details', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')'; $this->title = $prefix . __( 'Operation System Details', 'wp-piwik' ) . ' (' . $time_settings['description'] . ')';
$this->method = 'DevicesDetection.getOsVersions'; $this->method = 'DevicesDetection.getOsVersions';
$this->context = 'normal'; $this->context = 'normal';
wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
wp_enqueue_script ( 'wp-piwik-chartjs', self::$wpPiwik->getPluginURL () . 'js/chartjs/chart.min.js', "3.4.1" );
wp_enqueue_style('wp-piwik', self::$wpPiwik->getPluginURL().'css/wp-piwik.css',array(),self::$wpPiwik->getPluginVersion());
}
public function show() {
$response = self::$wpPiwik->request($this->apiID[$this->method]);
$tableBody = array();
if (!empty($response['result']) && $response['result'] ='error')
echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
else {
$tableHead = array(__('Operation System', 'wp-piwik'), __('Unique', 'wp-piwik'), __('Percent', 'wp-piwik'));
if (isset($response[0]['nb_uniq_visitors'])) $unique = 'nb_uniq_visitors';
else $unique = 'sum_daily_nb_uniq_visitors';
$count = 0;
$sum = 0;
$js = array();
$class = array();
if (is_array($response))
foreach ($response as $row) {
$count++;
$sum += isset($row[$unique])?$row[$unique]:0;
if ($count < $this->limit)
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
elseif (!isset($tableBody['Others'])) {
$tableBody['Others'] = array($row['label'], $row[$unique], 0);
$class['Others'] = 'wp-piwik-hideDetails';
$js['Others'] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
$class[$row['label']] = 'wp-piwik-hideDetails hidden';
$js[$row['label']] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
} else {
$tableBody['Others'][1] += $row[$unique];
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
$class[$row['label']] = 'wp-piwik-hideDetails hidden';
$js[$row['label']] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
}
}
if ($count > $this->limit)
$tableBody['Others'][0] = __('Others', 'wp-piwik');
foreach ($tableBody as $key => $row)
$tableBody[$key][2] = number_format($row[1]/$sum*100, 2).'%';
if (!empty($tableBody)) $this->pieChart($tableBody);
$this->table($tableHead, $tableBody, null, false, $js, $class);
}
}
$version = self::$wp_piwik->get_plugin_version();
wp_enqueue_script( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'js/wp-piwik.js', array(), $version, true );
wp_enqueue_script( 'wp-piwik-chartjs', self::$wp_piwik->get_plugin_url() . 'js/chartjs/chart.min.js', array(), $version, false );
wp_enqueue_style( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'css/wp-piwik.css', array(), $version );
} }
public function show() {
$response = self::$wp_piwik->request( $this->api_id[ $this->method ] );
$table_body = array();
if ( ! empty( $response['result'] ) && 'error' === $response['result'] ) {
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $response['message'] );
} else {
$table_head = array( __( 'Operation System', 'wp-piwik' ), __( 'Unique', 'wp-piwik' ), __( 'Percent', 'wp-piwik' ) );
if ( isset( $response[0]['nb_uniq_visitors'] ) ) {
$unique = 'nb_uniq_visitors';
} else {
$unique = 'sum_daily_nb_uniq_visitors';
}
$count = 0;
$sum = 0;
$js = array();
$css_class = array();
if ( is_array( $response ) ) {
foreach ( $response as $row ) {
++$count;
$sum += isset( $row[ $unique ] ) ? $row[ $unique ] : 0;
if ( $count < $this->limit ) {
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
} elseif ( ! isset( $table_body['Others'] ) ) {
$table_body['Others'] = array( $row['label'], $row[ $unique ], 0 );
$css_class['Others'] = 'wp-piwik-hideDetails';
$js['Others'] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
$css_class[ $row['label'] ] = 'wp-piwik-hideDetails hidden';
$js[ $row['label'] ] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
} else {
$table_body['Others'][1] += $row[ $unique ];
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
$css_class[ $row['label'] ] = 'wp-piwik-hideDetails hidden';
$js[ $row['label'] ] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
}
}
}
if ( $count > $this->limit ) {
$table_body['Others'][0] = __( 'Others', 'wp-piwik' );
}
foreach ( $table_body as $key => $row ) {
$table_body[ $key ][2] = number_format( $row[1] / $sum * 100, 2 ) . '%';
}
if ( ! empty( $table_body ) ) {
$this->pie_chart( $table_body );
}
$this->table( $table_head, $table_body, null, false, $js, $css_class );
}
}
}

View File

@ -2,65 +2,75 @@
namespace WP_Piwik\Widget; namespace WP_Piwik\Widget;
class Systems extends \WP_Piwik\Widget { class Systems extends \WP_Piwik\Widget {
protected function configure($prefix = '', $params = array()) { protected function configure( $prefix = '', $params = array() ) {
$timeSettings = $this->getTimeSettings(); $time_settings = $this->get_time_settings();
$this->parameter = array( $this->parameter = array(
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId), 'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
'period' => $timeSettings['period'], 'period' => $time_settings['period'],
'date' => $timeSettings['date'] 'date' => $time_settings['date'],
); );
$this->title = $prefix.__('Operation Systems', 'wp-piwik').' ('.__($timeSettings['description'],'wp-piwik').')'; $this->title = $prefix . __( 'Operation Systems', 'wp-piwik' ) . ' (' . $time_settings['description'] . ')';
$this->method = 'DevicesDetection.getOsFamilies'; $this->method = 'DevicesDetection.getOsFamilies';
$this->context = 'normal'; $this->context = 'normal';
wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL().'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
wp_enqueue_script ( 'wp-piwik-chartjs', self::$wpPiwik->getPluginURL () . 'js/chartjs/chart.min.js', "3.4.1" );
wp_enqueue_style('wp-piwik', self::$wpPiwik->getPluginURL().'css/wp-piwik.css',array(),self::$wpPiwik->getPluginVersion());
}
public function show() {
$response = self::$wpPiwik->request($this->apiID[$this->method]);
$tableBody = array();
if (!empty($response['result']) && $response['result'] ='error')
echo '<strong>'.__('Piwik error', 'wp-piwik').':</strong> '.htmlentities($response['message'], ENT_QUOTES, 'utf-8');
else {
$tableHead = array(__('Operation System', 'wp-piwik'), __('Unique', 'wp-piwik'), __('Percent', 'wp-piwik'));
if (isset($response[0]['nb_uniq_visitors'])) $unique = 'nb_uniq_visitors';
else $unique = 'sum_daily_nb_uniq_visitors';
$count = 0;
$sum = 0;
$js = array();
$class = array();
if (is_array($response))
foreach ($response as $row) {
$count++;
$sum += isset($row[$unique])?$row[$unique]:0;
if ($count < $this->limit)
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
elseif (!isset($tableBody['Others'])) {
$tableBody['Others'] = array($row['label'], $row[$unique], 0);
$class['Others'] = 'wp-piwik-hideDetails';
$js['Others'] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
$class[$row['label']] = 'wp-piwik-hideDetails hidden';
$js[$row['label']] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
} else {
$tableBody['Others'][1] += $row[$unique];
$tableBody[$row['label']] = array($row['label'], $row[$unique], 0);
$class[$row['label']] = 'wp-piwik-hideDetails hidden';
$js[$row['label']] = '$j'."( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
}
}
if ($count > $this->limit)
$tableBody['Others'][0] = __('Others', 'wp-piwik');
foreach ($tableBody as $key => $row)
$tableBody[$key][2] = number_format($row[1]/$sum*100, 2).'%';
if (!empty($tableBody)) $this->pieChart($tableBody);
$this->table($tableHead, $tableBody, null, false, $js, $class);
}
}
$version = self::$wp_piwik->get_plugin_version();
wp_enqueue_script( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'js/wp-piwik.js', array(), $version, true );
wp_enqueue_script( 'wp-piwik-chartjs', self::$wp_piwik->get_plugin_url() . 'js/chartjs/chart.min.js', array(), $version, false );
wp_enqueue_style( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'css/wp-piwik.css', array(), $version );
} }
public function show() {
$response = self::$wp_piwik->request( $this->api_id[ $this->method ] );
$table_body = array();
if ( ! empty( $response['result'] ) && 'error' === $response['result'] ) {
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $response['message'] );
} else {
$table_head = array( __( 'Operation System', 'wp-piwik' ), __( 'Unique', 'wp-piwik' ), __( 'Percent', 'wp-piwik' ) );
if ( isset( $response[0]['nb_uniq_visitors'] ) ) {
$unique = 'nb_uniq_visitors';
} else {
$unique = 'sum_daily_nb_uniq_visitors';
}
$count = 0;
$sum = 0;
$js = array();
$css_class = array();
if ( is_array( $response ) ) {
foreach ( $response as $row ) {
++$count;
$sum += isset( $row[ $unique ] ) ? $row[ $unique ] : 0;
if ( $count < $this->limit ) {
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
} elseif ( ! isset( $table_body['Others'] ) ) {
$table_body['Others'] = array( $row['label'], $row[ $unique ], 0 );
$css_class['Others'] = 'wp-piwik-hideDetails';
$js['Others'] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
$css_class[ $row['label'] ] = 'wp-piwik-hideDetails hidden';
$js[ $row['label'] ] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
} else {
$table_body['Others'][1] += $row[ $unique ];
$table_body[ $row['label'] ] = array( $row['label'], $row[ $unique ], 0 );
$css_class[ $row['label'] ] = 'wp-piwik-hideDetails hidden';
$js[ $row['label'] ] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
}
}
}
if ( $count > $this->limit ) {
$table_body['Others'][0] = __( 'Others', 'wp-piwik' );
}
foreach ( $table_body as $key => $row ) {
$table_body[ $key ][2] = number_format( $row[1] / $sum * 100, 2 ) . '%';
}
if ( ! empty( $table_body ) ) {
$this->pie_chart( $table_body );
}
$this->table( $table_head, $table_body, null, false, $js, $css_class );
}
}
}

View File

@ -4,77 +4,81 @@ namespace WP_Piwik\Widget;
use WP_Piwik\Widget; use WP_Piwik\Widget;
class Types extends Widget class Types extends Widget {
{
public $className = __CLASS__;
protected function configure($prefix = '', $params = array()) public $class_name = __CLASS__;
{
$timeSettings = $this->getTimeSettings();
$this->parameter = array(
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId),
'period' => $timeSettings['period'],
'date' => $timeSettings['date']
);
$this->title = $prefix . __('Types', 'wp-piwik') . ' (' . __($timeSettings['description'], 'wp-piwik') . ')';
$this->method = 'DevicesDetection.getType';
$this->context = 'normal';
wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL() . 'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
wp_enqueue_script('wp-piwik-chartjs', self::$wpPiwik->getPluginURL() . 'js/chartjs/chart.min.js', "3.4.1");
wp_enqueue_style('wp-piwik', self::$wpPiwik->getPluginURL() . 'css/wp-piwik.css', array(), self::$wpPiwik->getPluginVersion());
}
public function show() protected function configure( $prefix = '', $params = array() ) {
{ $time_settings = $this->get_time_settings();
$response = self::$wpPiwik->request($this->apiID[$this->method]); $this->parameter = array(
$tableBody = array(); 'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
if (!empty($response['result']) && $response['result'] = 'error') 'period' => $time_settings['period'],
echo '<strong>' . __('Piwik error', 'wp-piwik') . ':</strong> ' . htmlentities($response['message'], ENT_QUOTES, 'utf-8'); 'date' => $time_settings['date'],
else { );
$tableHead = array(__('Type', 'wp-piwik'), __('Unique', 'wp-piwik'), __('Percent', 'wp-piwik')); $this->title = $prefix . __( 'Types', 'wp-piwik' ) . ' (' . $time_settings['description'] . ')';
if (isset($response[0]['nb_uniq_visitors'])) { $this->method = 'DevicesDetection.getType';
$unique = 'nb_uniq_visitors'; $this->context = 'normal';
} else {
$unique = 'sum_daily_nb_uniq_visitors';
}
$count = 0;
$sum = 0;
$js = array();
$class = array();
if (is_array($response))
foreach ($response as $row) {
$key = isset($row[$unique]) ? $unique : "nb_visits";
$count++;
$sum += isset($row[$key]) ? $row[$key] : 0;
if ($count < $this->limit)
$tableBody[$row['label']] = array($row['label'], $row[$key], 0);
elseif (!isset($tableBody['Others'])) {
$tableBody['Others'] = array($row['label'], $row[$key], 0);
$class['Others'] = 'wp-piwik-hideDetails';
$js['Others'] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
$tableBody[$row['label']] = array($row['label'], $row[$key], 0);
$class[$row['label']] = 'wp-piwik-hideDetails hidden';
$js[$row['label']] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
} else {
$tableBody['Others'][1] += $row[$key];
$tableBody[$row['label']] = array($row['label'], $row[$key], 0);
$class[$row['label']] = 'wp-piwik-hideDetails hidden';
$js[$row['label']] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
}
}
if ($count > $this->limit) {
$tableBody['Others'][0] = __('Others', 'wp-piwik');
} elseif ($count == $this->limit) {
$class['Others'] = $js['Others'] = '';
}
foreach ($tableBody as $key => $row) $version = self::$wp_piwik->get_plugin_version();
$tableBody[$key][2] = number_format($row[1] / $sum * 100, 2) . '%'; wp_enqueue_script( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'js/wp-piwik.js', array(), $version, true );
wp_enqueue_script( 'wp-piwik-chartjs', self::$wp_piwik->get_plugin_url() . 'js/chartjs/chart.min.js', array(), $version, false );
wp_enqueue_style( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'css/wp-piwik.css', array(), $version );
}
if (!empty($tableBody)) $this->pieChart($tableBody); public function show() {
$this->table($tableHead, $tableBody, null, false, $js, $class); $response = self::$wp_piwik->request( $this->api_id[ $this->method ] );
} $table_body = array();
} if ( ! empty( $response['result'] ) && 'error' === $response['result'] ) {
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $response['message'] );
} else {
$table_head = array( __( 'Type', 'wp-piwik' ), __( 'Unique', 'wp-piwik' ), __( 'Percent', 'wp-piwik' ) );
if ( isset( $response[0]['nb_uniq_visitors'] ) ) {
$unique = 'nb_uniq_visitors';
} else {
$unique = 'sum_daily_nb_uniq_visitors';
}
$count = 0;
$sum = 0;
$js = array();
$css_class = array();
if ( is_array( $response ) ) {
foreach ( $response as $row ) {
$key = isset( $row[ $unique ] ) ? $unique : 'nb_visits';
++$count;
$sum += isset( $row[ $key ] ) ? $row[ $key ] : 0;
if ( $count < $this->limit ) {
$table_body[ $row['label'] ] = array( $row['label'], $row[ $key ], 0 );
} elseif ( ! isset( $table_body['Others'] ) ) {
$table_body['Others'] = array( $row['label'], $row[ $key ], 0 );
$css_class['Others'] = 'wp-piwik-hideDetails';
$js['Others'] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
$table_body[ $row['label'] ] = array( $row['label'], $row[ $key ], 0 );
$css_class[ $row['label'] ] = 'wp-piwik-hideDetails hidden';
$js[ $row['label'] ] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
} else {
$table_body['Others'][1] += $row[ $key ];
$table_body[ $row['label'] ] = array( $row['label'], $row[ $key ], 0 );
$css_class[ $row['label'] ] = 'wp-piwik-hideDetails hidden';
$js[ $row['label'] ] = '$j' . "( '.wp-piwik-hideDetails' ).toggle( 'hidden' );";
}
}
}
if ( $count > $this->limit ) {
$table_body['Others'][0] = __( 'Others', 'wp-piwik' );
} elseif ( $count === $this->limit ) {
$css_class['Others'] = '';
$js['Others'] = '';
}
foreach ( $table_body as $key => $row ) {
$table_body[ $key ][2] = number_format( $row[1] / $sum * 100, 2 ) . '%';
}
if ( ! empty( $table_body ) ) {
$this->pie_chart( $table_body );
}
$this->table( $table_head, $table_body, null, false, $js, $css_class );
}
}
} }

View File

@ -4,76 +4,97 @@ namespace WP_Piwik\Widget;
use WP_Piwik\Widget; use WP_Piwik\Widget;
class Visitors extends Widget class Visitors extends Widget {
{
public $className = __CLASS__; public $class_name = __CLASS__;
protected function configure($prefix = '', $params = array()) protected function configure( $prefix = '', $params = array() ) {
{ $time_settings = $this->get_time_settings();
$timeSettings = $this->getTimeSettings(); $this->parameter = array(
$this->parameter = array( 'idSite' => self::$wp_piwik->get_piwik_site_id( $this->blog_id ),
'idSite' => self::$wpPiwik->getPiwikSiteId($this->blogId), 'period' => isset( $params['period'] ) ? $params['period'] : $time_settings['period'],
'period' => isset($params['period']) ? $params['period'] : $timeSettings['period'], 'date' => 'last' . ( 'day' === $time_settings['period'] ? '30' : '12' ),
'date' => 'last' . ($timeSettings['period'] == 'day' ? '30' : '12'), 'limit' => null,
'limit' => null );
); $this->title = $prefix . __( 'Visitors', 'wp-piwik' ) . ' (' . $this->range_name() . ')';
$this->title = $prefix . __('Visitors', 'wp-piwik') . ' (' . __($this->rangeName(), 'wp-piwik') . ')'; $this->method = array( 'VisitsSummary.getVisits', 'VisitsSummary.getUniqueVisitors', 'VisitsSummary.getBounceCount', 'VisitsSummary.getActions' );
$this->method = array('VisitsSummary.getVisits', 'VisitsSummary.getUniqueVisitors', 'VisitsSummary.getBounceCount', 'VisitsSummary.getActions'); $this->context = 'normal';
$this->context = 'normal';
wp_enqueue_script('wp-piwik', self::$wpPiwik->getPluginURL() . 'js/wp-piwik.js', array(), self::$wpPiwik->getPluginVersion(), true);
wp_enqueue_script('wp-piwik-chartjs', self::$wpPiwik->getPluginURL() . 'js/chartjs/chart.min.js', "3.4.1");
wp_enqueue_style('wp-piwik', self::$wpPiwik->getPluginURL() . 'css/wp-piwik.css', array(), self::$wpPiwik->getPluginVersion());
}
public function requestData() $version = self::$wp_piwik->get_plugin_version();
{ wp_enqueue_script( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'js/wp-piwik.js', array(), $version, true );
$response = array(); wp_enqueue_script( 'wp-piwik-chartjs', self::$wp_piwik->get_plugin_url() . 'js/chartjs/chart.min.js', array(), $version, false );
$success = true; wp_enqueue_style( 'wp-piwik', self::$wp_piwik->get_plugin_url() . 'css/wp-piwik.css', array(), $version );
foreach ($this->method as $method) { }
$response[$method] = self::$wpPiwik->request($this->apiID[$method]);
if (!empty($response[$method]['result']) && $response[$method]['result'] = 'error')
$success = false;
}
return array("response" => $response, "success" => $success);
}
public function show() public function request_data() {
{ $response = array();
$result = $this->requestData(); $success = true;
$response = $result["response"]; foreach ( $this->method as $method ) {
if (!$result["success"]) { $response[ $method ] = self::$wp_piwik->request( $this->api_id[ $method ] );
echo '<strong>' . __('Piwik error', 'wp-piwik') . ':</strong> ' . htmlentities($response[$method]['message'], ENT_QUOTES, 'utf-8'); if ( ! empty( $response[ $method ]['result'] ) && 'error' === $response[ $method ]['result'] ) {
} else { $success = false;
$data = array(); }
if (is_array($response) && is_array($response['VisitsSummary.getVisits'])) }
foreach ($response['VisitsSummary.getVisits'] as $key => $value) { return array(
if ($this->parameter['period'] == 'week') { 'response' => $response,
preg_match("/[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/", $key, $dateList); 'success' => $success,
$jsKey = $dateList[0]; );
$textKey = $this->dateFormat($jsKey, 'week'); }
} elseif ($this->parameter['period'] == 'month') {
$jsKey = $key . '-01';
$textKey = $key;
} else $jsKey = $textKey = $key;
$data[] = array(
$textKey,
$value,
$response['VisitsSummary.getUniqueVisitors'][$key] ? $response['VisitsSummary.getUniqueVisitors'][$key] : '-',
$response['VisitsSummary.getBounceCount'][$key] ? $response['VisitsSummary.getBounceCount'][$key] : '-',
$response['VisitsSummary.getActions'][$key] ? $response['VisitsSummary.getActions'][$key] : '-'
);
$javaScript[] = 'javascript:wp_piwik_datelink(\'' . urlencode('wp-piwik_stats') . '\',\'' . str_replace('-', '', $jsKey) . '\',\'' . (isset($_GET['wpmu_show_stats']) ? (int)$_GET['wpmu_show_stats'] : '') . '\');';
}
$this->table(
array(__('Date', 'wp-piwik'), __('Visits', 'wp-piwik'), __('Unique', 'wp-piwik'), __('Bounced', 'wp-piwik'), __('Page Views', 'wp-piwik')),
array_reverse($data),
array(),
'clickable',
array_reverse(isset($javaScript) ? $javaScript : [])
);
}
} public function show() {
$result = $this->request_data();
$response = $result['response'];
if ( ! $result['success'] ) {
$message = '';
if ( is_array( $this->method ) ) {
foreach ( $this->method as $m ) {
if ( empty( $response[ $m ]['message'] ) ) {
continue;
}
$message .= ' ' . $m . ' - ' . $response[ $m ]['message'];
}
} else {
$message = $response[ $this->method ]['message'];
}
echo '<strong>' . esc_html__( 'Piwik error', 'wp-piwik' ) . ':</strong> ' . esc_html( $message );
} else {
$data = array();
if ( is_array( $response ) && is_array( $response['VisitsSummary.getVisits'] ) ) {
foreach ( $response['VisitsSummary.getVisits'] as $key => $value ) {
if ( 'week' === $this->parameter['period'] ) {
preg_match( '/[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])/', $key, $date_list );
$js_key = $date_list[0];
$text_key = $this->date_format( $js_key, 'week' );
} elseif ( 'month' === $this->parameter['period'] ) {
$js_key = $key . '-01';
$text_key = $key;
} else {
$js_key = $key;
$text_key = $key;
}
$data[] = array(
$text_key,
$value,
$response['VisitsSummary.getUniqueVisitors'][ $key ] ? $response['VisitsSummary.getUniqueVisitors'][ $key ] : '-',
$response['VisitsSummary.getBounceCount'][ $key ] ? $response['VisitsSummary.getBounceCount'][ $key ] : '-',
$response['VisitsSummary.getActions'][ $key ] ? $response['VisitsSummary.getActions'][ $key ] : '-',
);
$java_script[] = 'javascript:wp_piwik_datelink('
. wp_json_encode( rawurlencode( 'wp-piwik_stats' ) ) . ','
. wp_json_encode( str_replace( '-', '', $js_key ) ) . ','
. wp_json_encode( isset( $_GET['wpmu_show_stats'] ) ? (int) $_GET['wpmu_show_stats'] : '' )
. ');';
}
}
$this->table(
array( __( 'Date', 'wp-piwik' ), __( 'Visits', 'wp-piwik' ), __( 'Unique', 'wp-piwik' ), __( 'Bounced', 'wp-piwik' ), __( 'Page Views', 'wp-piwik' ) ),
array_reverse( $data ),
array(),
'clickable',
array_reverse( isset( $java_script ) ? $java_script : array() )
);
}
}
} }

View File

@ -0,0 +1,20 @@
{
"require": {
"dealerdirect/phpcodesniffer-composer-installer": "^1.2",
"phpcompatibility/phpcompatibility-wp": "^2.1",
"squizlabs/php_codesniffer": "^3.13",
"wp-coding-standards/wpcs": "^3.3",
"friendsofphp/php-cs-fixer": "^3.94"
},
"config": {
"allow-plugins": {
"dealerdirect/phpcodesniffer-composer-installer": true,
"phpstan/extension-installer": true
}
},
"require-dev": {
"phpstan/phpstan": "^2.1",
"szepeviktor/phpstan-wordpress": "^2.0",
"phpstan/extension-installer": "^1.4"
}
}

3529
wp-content/plugins/wp-piwik/composer.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +1,11 @@
<?php <?php
/****************************************************** /******************************************************
* Configure WP-Piwik Logger * Configure WP-Piwik Logger
* 0: Logger disabled * 0: Logger disabled
* 1: Log to screen * 1: Log to screen
* 2: Log to file (logs/YYYYMMDD_wp-piwik.log) * 2: Log to file (logs/YYYYMMDD_wp-piwik.log)
*
* @package WP_Piwik
******************************************************/ ******************************************************/
define ( 'WP_PIWIK_ACTIVATE_LOGGER', 0 );
define( 'WP_PIWIK_ACTIVATE_LOGGER', 0 );

View File

@ -56,19 +56,10 @@ input.wp-piwik-wide {
width:100%; width:100%;
} }
div.wp-piwik-donate { .wp-matomo-inline-notice {
float:right; padding: 1em;
width:220px;
background:#ffc;
padding:10px;
border:1px solid black;
margin: 10px 10px;
} }
div.wp-piwik-donate div { .wp-matomo-inline-notice.wp-matomo-warning {
width:190px; background-color: rgba(255, 165, 0, 0.2);
text-align:center;
border:solid black;
border-width:1px 0 0 0 ;
padding:5px
} }

View File

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

View File

@ -0,0 +1,2 @@
tests/ export-ignore
run_tests.sh export-ignore

View File

@ -0,0 +1,5 @@
/.idea/
/vendor/
.phpunit.result.cache
/tests/.phpunit.result.cache
composer.lock

View File

@ -0,0 +1,30 @@
# Matomo PHP Tracker Changelog
This is the Developer Changelog for Matomo PHP Tracker. All breaking changes or new features are listed below.
## Matomo PHP Tracker 3.3.2
### Changed
- Support for formFactors client hint parameter, supported as of Matomo 5.2.0
## Matomo PHP Tracker 3.3.1
### Fixed
- closed curl connection
## Matomo PHP Tracker 3.3.0
### Removed
- support for PHP versions lower than 7.2
### Changed
- all `MatomoTracker` class constants are now explicitly public
- all `MatomoTracker` dynamic properties are now explicitly public
## Matomo PHP Tracker 3.0.0
Attention: This version of Matomo PHP Tracker is no longer compatible with Matomo 3.x or earlier
- Support for new page performance metrics (added in Matomo 4) has been added. You can use `setPerformanceTimings()` to set them for page views.
- Setting page generation time using `setGenerationTime()` has been discontinued. The method still exists to not break applications still using it, but it does not have any effect. Please use new page performance metrics as replacement.
- Sending requests using cURL will now throw an exception if an error occurs in a request.
- Matomo does not longer support tracking of these browser plugins: Gears, Director. Therefor the signature of `setPlugins()` changed.
- Implementation of ecommerce views changed from custom variables to raw parameters
- It is now possible to configure cookie options for Secure, HTTPOnly and SameSite.
- Add method setRequestMethodNonBulk() to allow (non bulk) POST requests.

View File

@ -0,0 +1,27 @@
Copyright (c) 2014, Matomo Open Source Analytics
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the {organization} nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,51 @@
<?php
namespace WP_Piwik {
/**
* Matomo - free/libre analytics platform
*
* For more information, see README.md
*
* @license released under BSD License http://www.opensource.org/licenses/bsd-license.php
* @link https://matomo.org/docs/tracking-api/
*
* @category Matomo
* @package MatomoTracker
*/
if (!\class_exists('\\WP_Piwik\\MatomoTracker')) {
include_once 'MatomoTracker.php';
}
/**
* Helper function to quickly generate the URL to track a page view.
*
* @deprecated
* @param $idSite
* @param string $documentTitle
* @return string
*/
function Piwik_getUrlTrackPageView($idSite, $documentTitle = '')
{
return \WP_Piwik\Matomo_getUrlTrackPageView($idSite, $documentTitle);
}
/**
* Helper function to quickly generate the URL to track a goal.
*
* @deprecated
* @param $idSite
* @param $idGoal
* @param float $revenue
* @return string
*/
function Piwik_getUrlTrackGoal($idSite, $idGoal, $revenue = 0.0)
{
return \WP_Piwik\Matomo_getUrlTrackGoal($idSite, $idGoal, $revenue);
}
/**
* For BC only
*
* @deprecated use MatomoTracker instead
*/
class PiwikTracker extends MatomoTracker
{
}
}

View File

@ -0,0 +1,53 @@
# PHP Client for Matomo Analytics Tracking API
The PHP Tracker Client provides all features of the [Matomo Javascript Tracker](https://developer.matomo.org/api-reference/tracking-javascript), such as Ecommerce Tracking, Custom Variables, Event Tracking and more.
## Documentation and examples
Check out our [Matomo-PHP-Tracker developer documentation](https://developer.matomo.org/api-reference/PHP-Piwik-Tracker) and [Matomo Tracking API guide](https://matomo.org/docs/tracking-api/).
```php
// Required variables
$matomoSiteId = 6; // Site ID
$matomoUrl = "https://example.tld"; // Your matomo URL
$matomoToken = ""; // Your authentication token
// Optional variable
$matomoPageTitle = ""; // The title of the page
// Load object
require_once("MatomoTracker.php");
// Matomo object
$matomoTracker = new MatomoTracker((int)$matomoSiteId, $matomoUrl);
// Set authentication token
$matomoTracker->setTokenAuth($matomoToken);
// Track page view
$matomoTracker->doTrackPageView($matomoPageTitle);
```
## Requirements:
* JSON extension (json_decode, json_encode)
* cURL or stream extension (to issue the HTTPS request to Matomo)
## Installation
### Composer
```
composer require matomo/matomo-php-tracker
```
### Manually
Alternatively, you can download the files and require the Matomo tracker manually:
```
require_once("MatomoTracker.php");
```
## License
Released under the [BSD License](https://opensource.org/licenses/BSD-3-Clause)

View File

@ -0,0 +1,44 @@
{
"name": "matomo\/matomo-php-tracker",
"description": "PHP Client for Matomo Analytics Tracking API",
"keywords": [
"matomo",
"piwik",
"tracker",
"analytics"
],
"homepage": "https:\/\/matomo.org",
"license": "BSD-3-Clause",
"authors": [
{
"name": "The Matomo Team",
"email": "hello@matomo.org",
"homepage": "https:\/\/matomo.org\/team\/"
}
],
"support": {
"forum": "https:\/\/forum.matomo.org\/",
"issues": "https:\/\/github.com\/matomo-org\/matomo-php-tracker\/issues",
"source": "https:\/\/github.com\/matomo-org\/matomo-php-tracker"
},
"require": {
"php": "^7.2 || ^8.0",
"ext-json": "*"
},
"suggest": {
"ext-curl": "Using this extension to issue the HTTPS request to Matomo"
},
"autoload": {
"classmap": [
"."
]
},
"autoload-dev": {
"psr-4": {
"\\": "tests\/"
}
},
"require-dev": {
"phpunit\/phpunit": "^8.5 || ^9.3 || ^10.1"
}
}

View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
backupGlobals="true"
verbose="true">
<testsuites>
<testsuite name="UnitTests">
<directory>./tests/Unit</directory>
</testsuite>
</testsuites>
</phpunit>

View File

@ -0,0 +1,108 @@
<?php
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
* @package matomo
*/
/**
* This script, when included or visited, will send an AI bot tracking
* request to Matomo in a shutdown function.
*
* It will only send this request if the current user agent is for a
* known AI bot.
*
* This script can be added to a user's wp-config.php or be executed
* via an HTTP request in an <esi:include> directive. It should have as
* few dependencies as possible, and load as few PHP files as possible.
*
* phpcs:disable WordPress.WP.GlobalVariablesOverride.Prohibited
*/
function wp_piwik_track_if_ai_bot() {
global $wpdb;
if (
( ! defined( 'WP_CACHE' ) || ! WP_CACHE )
&& empty( $_GET['mtm_esi'] )
) { // advanced-cache.php not in use and we are not tracking via esi:include
return;
}
if ( isset( $_GET['mtm_esi'] ) ) { // executing via esi:include directive
$GLOBALS['WP_PIWIK_IN_ESI'] = true;
}
require_once __DIR__ . '/../libs/matomo-php-tracker/MatomoTracker.php';
// check user agent is AI bot first thing, so if it is a normal request we do
// as little extra work as possible
// phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash
$user_agent = ! empty( $_SERVER['HTTP_USER_AGENT'] ) ? stripslashes( $_SERVER['HTTP_USER_AGENT'] ) : '';
if ( ! \WP_Piwik\MatomoTracker::isUserAgentAIBot( $user_agent ) ) {
return;
}
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
$GLOBALS['wp_plugin_paths'] = array();
if ( ! defined( 'ABSPATH' ) ) {
// being called from a esi:include directive
define( 'SHORTINIT', true );
$wp_config_file = dirname( dirname( dirname( dirname( __DIR__ ) ) ) ) . '/wp-config.php';
if ( ! is_file( $wp_config_file ) && ! empty( $_SERVER['SCRIPT_FILENAME'] ) ) {
// phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash
$script_filename = stripslashes( $_SERVER['SCRIPT_FILENAME'] );
$wp_config_file = dirname( dirname( dirname( dirname( dirname( $script_filename ) ) ) ) ) . '/wp-config.php';
}
require_once $wp_config_file;
} else {
// being called from request that uses advanced-cache.php
require_once ABSPATH . WPINC . '/class-wp-list-util.php';
require_once ABSPATH . WPINC . '/class-wp-token-map.php';
require_once ABSPATH . WPINC . '/formatting.php';
require_once ABSPATH . WPINC . '/functions.php';
}
require_once ABSPATH . WPINC . '/link-template.php';
require_once ABSPATH . WPINC . '/general-template.php';
require_once ABSPATH . WPINC . '/http.php';
require_once ABSPATH . WPINC . '/class-wp-http.php';
require_once ABSPATH . WPINC . '/class-wp-http-streams.php';
require_once ABSPATH . WPINC . '/class-wp-http-curl.php';
require_once ABSPATH . WPINC . '/class-wp-http-proxy.php';
require_once ABSPATH . WPINC . '/class-wp-http-cookie.php';
require_once ABSPATH . WPINC . '/class-wp-http-encoding.php';
require_once ABSPATH . WPINC . '/class-wp-http-response.php';
require_once ABSPATH . WPINC . '/class-wp-http-requests-response.php';
require_once ABSPATH . WPINC . '/class-wp-http-requests-hooks.php';
require_once __DIR__ . '/../wp-piwik.php';
if ( empty( $wpdb ) ) {
require_wp_db();
wp_set_wpdb_vars();
}
wp_start_object_cache();
if ( ! defined( 'WPMU_PLUGIN_DIR' ) ) {
wp_plugin_directory_constants();
}
// url is passed to tracker so we don't want to modify it
// phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
$url = ! empty( $_REQUEST['mtm_url'] ) ? wp_unslash( $_REQUEST['mtm_url'] ) : null;
$wp_piwik = new \WP_Piwik();
$settings = new \WP_Piwik\Settings( $wp_piwik );
$ai_bot_tracking = new \WP_Piwik\AIBotTracking( $settings, \WP_Piwik::get_logger() );
$ai_bot_tracking->do_ai_bot_tracking( $url );
}
register_shutdown_function( 'wp_piwik_track_if_ai_bot' );

View File

@ -0,0 +1,131 @@
{
"name": "wp-matomo",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"devDependencies": {
"@fastify/pre-commit": "^2.2.1"
}
},
"node_modules/@fastify/pre-commit": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/@fastify/pre-commit/-/pre-commit-2.2.1.tgz",
"integrity": "sha512-EluAZU4mFnCJfb6RyWFpWvEIAwdchipoiWMSRkQEaQ6ubbf6UVzYuXKSSZJR36SgtgZmKV5oRMxxwMNta5hskg==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fastify"
},
{
"type": "opencollective",
"url": "https://opencollective.com/fastify"
}
],
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
"cross-spawn": "^7.0.3",
"which": "^5.0.0"
}
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
"integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
"dev": true,
"license": "MIT",
"dependencies": {
"path-key": "^3.1.0",
"shebang-command": "^2.0.0",
"which": "^2.0.1"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/cross-spawn/node_modules/isexe": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
"integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
"dev": true,
"license": "ISC"
},
"node_modules/cross-spawn/node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
"integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
"dev": true,
"license": "ISC",
"dependencies": {
"isexe": "^2.0.0"
},
"bin": {
"node-which": "bin/node-which"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/isexe": {
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/isexe/-/isexe-3.1.5.tgz",
"integrity": "sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w==",
"dev": true,
"license": "BlueOak-1.0.0",
"engines": {
"node": ">=18"
}
},
"node_modules/path-key": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
"integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/shebang-command": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
"integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
"dev": true,
"license": "MIT",
"dependencies": {
"shebang-regex": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/shebang-regex": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
"integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/which": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/which/-/which-5.0.0.tgz",
"integrity": "sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ==",
"dev": true,
"license": "ISC",
"dependencies": {
"isexe": "^3.1.1"
},
"bin": {
"node-which": "bin/which.js"
},
"engines": {
"node": "^18.17.0 || >=20.5.0"
}
}
}
}

View File

@ -0,0 +1,12 @@
{
"scripts": {
"phpcs": "./vendor/bin/phpcs",
"phpcbf": "./vendor/bin/phpcbf"
},
"devDependencies": {
"@fastify/pre-commit": "^2.2.1"
},
"pre-commit": [
"phpcs"
]
}

View File

@ -1,5 +1,8 @@
<?php <?php
$wpRootDir = isset($wpRootDir)?$wpRootDir:'../../../../'; // Get the install directory of WP.
// Usefull for immutable WP install, like : https://github.com/zorglube/clever-wordpress OR https://github.com/CleverCloud/wordpress-bedrock-example where WP core and Plugins are in separate directories
$wpRootDir = getenv('WP_MATOMO_WP_ROOT_DIR');
$wpRootDir = !empty($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');
@ -11,29 +14,31 @@ $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->get_global_option ( 'piwik_mode' )) {
case 'php' : case 'php' :
$PIWIK_URL = $settings->getGlobalOption ( 'proxy_url' ); $PIWIK_URL = $settings->get_global_option ( 'proxy_url' );
break; break;
case 'cloud' : case 'cloud' :
$PIWIK_URL = 'https://' . $settings->getGlobalOption ( 'piwik_user' ) . '.innocraft.cloud/'; $PIWIK_URL = 'https://' . $settings->get_global_option ( '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->get_global_option ( 'matomo_user' ) . '.matomo.cloud/';
break; break;
default : default :
$PIWIK_URL = $settings->getGlobalOption ( 'piwik_url' ); $PIWIK_URL = $settings->get_global_option ( 'piwik_url' );
break;
} }
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->get_global_option ( 'piwik_token' );
$timeout = $settings->getGlobalOption ( 'connection_timeout' ); $timeout = $settings->get_global_option ( '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->get_global_option('http_connection') == 'curl') || (function_exists('curl_init') && !ini_get('allow_url_fopen'))
); );
$settings->getGlobalOption ( 'http_connection' ); $settings->get_global_option ( 'http_connection' );
ini_set ( 'display_errors', 0 ); ini_set ( 'display_errors', 0 );

View File

@ -126,6 +126,10 @@ if (strpos($path, 'piwik.php') === 0 || strpos($path, 'matomo.php') === 0) {
'cip' => getVisitIp(), 'cip' => getVisitIp(),
'token_auth' => $TOKEN_AUTH, 'token_auth' => $TOKEN_AUTH,
); );
if (!isset($_GET['token_auth']) && !isset($_POST['token_auth'])) {
sanitizeTrackingOverrideParams($_GET);
}
} }
$url = $MATOMO_URL . $path; $url = $MATOMO_URL . $path;
@ -293,8 +297,14 @@ function getHttpContentAndStatus($url, $timeout, $user_agent)
// if there's POST data, send our proxy request as a POST // if there's POST data, send our proxy request as a POST
if (!empty($_POST)) { if (!empty($_POST)) {
$postBody = file_get_contents("php://input"); $postBody = file_get_contents("php://input");
if (!isset($_GET['token_auth']) && !isset($_POST['token_auth'])) {
$didSanitizePostParams = sanitizeTrackingOverrideParams($_POST);
if ($didSanitizePostParams) {
$postBody = http_build_query($_POST);
}
}
$stream_options['http']['method'] = 'POST'; $stream_options['http']['method'] = 'POST';
$stream_options['http']['header'][] = "Content-type: application/x-www-form-urlencoded"; $stream_options['http']['header'][] = "Content-type: application/x-www-form-urlencoded";
$stream_options['http']['header'][] = "Content-Length: " . strlen($postBody); $stream_options['http']['header'][] = "Content-Length: " . strlen($postBody);
$stream_options['http']['content'] = $postBody; $stream_options['http']['content'] = $postBody;
@ -365,6 +375,20 @@ function getHttpContentAndStatus($url, $timeout, $user_agent)
} }
function sanitizeTrackingOverrideParams(&$params)
{
$didSanitizeParams = false;
$queryParamsToUnset = ['cdt', 'country', 'region', 'city', 'lat', 'long', 'cip'];
foreach ($queryParamsToUnset as $queryParamToUnset) {
if (isset($params[$queryParamToUnset])) {
unset($params[$queryParamToUnset]);
$didSanitizeParams = true;
}
}
return $didSanitizeParams;
}
function sendHeader($header, $replace = true) function sendHeader($header, $replace = true)
{ {
headers_sent() || header($header, $replace); headers_sent() || header($header, $replace);

View File

@ -1,9 +1,9 @@
=== Connect Matomo (WP-Matomo, WP-Piwik) === === Connect Matomo - Analytics Dashboard for WordPress ===
Contributors: Braekling Contributors: Braekling
Requires at least: 5.0 Requires at least: 5.0
Tested up to: 6.3 Tested up to: 6.9.4
Stable tag: 1.0.30 Stable tag: 1.1.5
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
@ -11,6 +11,8 @@ Adds Matomo (former Piwik) statistics to your WordPress dashboard and is also ab
== Description == == Description ==
**Version 1.1.4 includes several important security related fixes, it is highly recommended to update to this version.**
If you are not yet using Matomo On-Premise, Matomo Cloud or hosting your own instance of Matomo, please use the [Matomo for WordPress plugin](https://wordpress.org/plugins/matomo/). If you are not yet using Matomo On-Premise, Matomo Cloud or hosting your own instance of Matomo, please use the [Matomo for WordPress plugin](https://wordpress.org/plugins/matomo/).
This plugin uses the Matomo API to show your Matomo statistics in your WordPress dashboard. It's also able to add the Matomo tracking code to your blog and to do some modifications to the tracking code. Additionally, WP-Matomo supports WordPress networks and manages multiple sites and their tracking codes. This plugin uses the Matomo API to show your Matomo statistics in your WordPress dashboard. It's also able to add the Matomo tracking code to your blog and to do some modifications to the tracking code. Additionally, WP-Matomo supports WordPress networks and manages multiple sites and their tracking codes.
@ -145,6 +147,33 @@ Add WP-Matomo to your /wp-content/plugins folder and enable it as [Network Plugi
== Changelog == == Changelog ==
= 1.1.5 =
* Update Matomo logo and screenshots.
* Update tracker proxy code with latest changes.
* Ensure query strings are correctly created when arg_separator.input is not '&'.
= 1.1.4 =
* Bug fix: fix URL to settings displayed upon installation.
* Remove donation form.
* Several assorted security related fixes.
= 1.1.3 =
* Replaced wp_unslash with stripslashes to address cases where wp_unslash may be undefined.
= 1.1.2 =
* Allow $wpRootDir variable in the proxy config.php file to be defined by the WP_MATOMO_WP_ROOT_DIR environment variable if present.
* Using phpcs and phpstan fix several issues including several vulnerabilities.
= 1.1.1 =
* Security bug fix: convert custom variable name and values to JSON before using in tracking code.
= 1.1.0 =
* Support for tracking AI bots to Matomo.
= 1.0.31 =
* Do not display value of persisted Matomo token in settings page.
* Fix notice when persisted notifications value is for some reason not an array.
= 1.0.30 = = 1.0.30 =
* Fix settings behavior * Fix settings behavior
* Fix auto configuration in PHP API mode * Fix auto configuration in PHP API mode

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

View File

@ -1,108 +1,129 @@
<?php <?php
/**
* Uninstall script.
*
* @package wp-piwik
*/
// Check if uninstall call is valid // Check if uninstall call is valid
if ( !defined( 'WP_UNINSTALL_PLUGIN' ) ) if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
exit(); exit();
$globalSettings = array(
'revision',
'last_settings_update',
'piwik_mode',
'piwik_url',
'piwik_path',
'piwik_user',
'matomo_user',
'piwik_token',
'auto_site_config',
'default_date',
'stats_seo',
'dashboard_widget',
'dashboard_chart',
'dashboard_seo',
'toolbar',
'capability_read_stats',
'perpost_stats',
'plugin_display_name',
'piwik_shortcut',
'shortcodes',
'track_mode',
'track_codeposition',
'track_noscript',
'track_nojavascript',
'proxy_url',
'track_content',
'track_search',
'track_404',
'add_post_annotations',
'add_customvars_box',
'add_download_extensions',
'disable_cookies',
'limit_cookies',
'limit_cookies_visitor',
'limit_cookies_session',
'limit_cookies_referral',
'track_admin',
'capability_stealth',
'track_across',
'track_across_alias',
'track_crossdomain_linking',
'track_feed',
'track_feed_addcampaign',
'track_feed_campaign',
'cache',
'disable_timelimit',
'connection_timeout',
'disable_ssl_verify',
'disable_ssl_verify_host',
'piwik_useragent',
'piwik_useragent_string',
'track_datacfasync',
'track_cdnurl',
'track_cdnurlssl',
'force_protocol'
);
$settings = array (
'name',
'site_id',
'noscript_code',
'tracking_code',
'last_tracking_code_update',
'dashboard_revision'
);
global $wpdb;
if (function_exists('is_multisite') && is_multisite()) {
if ($limit && $page)
$queryLimit = 'LIMIT '.(int) (($page - 1) * $limit).','.(int) $limit.' ';
$aryBlogs = $wpdb->get_results('SELECT blog_id FROM '.$wpdb->blogs.' '.$queryLimit.'ORDER BY blog_id', ARRAY_A);
if (is_array($aryBlogs))
foreach ($aryBlogs as $aryBlog) {
foreach ($settings as $key) {
delete_blog_option($aryBlog['blog_id'], 'wp-piwik-'.$key);
}
switch_to_blog($aryBlog['blog_id']);
$wpdb->query("DELETE FROM $wpdb->postmeta WHERE meta_key LIKE 'wp-piwik_%'");
$wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_wp-piwik_%'");
$wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_timeout_wp-piwik_%'");
restore_current_blog();
}
foreach ($globalSettings as $key)
delete_site_option('wp-piwik_global-'.$key);
delete_site_option('wp-piwik-manually');
delete_site_option('wp-piwik-notices');
} }
foreach ($settings as $key) /**
delete_option('wp-piwik-'.$key); * @return void
* @phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery
* @phpcs:disable WordPress.DB.DirectDatabaseQuery.NoCaching
*/
function wp_matomo_uninstall() {
global $wpdb;
foreach ($globalSettings as $key) $global_settings = array(
delete_option('wp-piwik_global-'.$key); 'revision',
'last_settings_update',
'piwik_mode',
'piwik_url',
'piwik_path',
'piwik_user',
'matomo_user',
'piwik_token',
'auto_site_config',
'default_date',
'stats_seo',
'dashboard_widget',
'dashboard_chart',
'dashboard_seo',
'toolbar',
'capability_read_stats',
'perpost_stats',
'plugin_display_name',
'piwik_shortcut',
'shortcodes',
'track_mode',
'track_codeposition',
'track_noscript',
'track_nojavascript',
'proxy_url',
'track_content',
'track_search',
'track_404',
'add_post_annotations',
'add_customvars_box',
'add_download_extensions',
'disable_cookies',
'limit_cookies',
'limit_cookies_visitor',
'limit_cookies_session',
'limit_cookies_referral',
'track_admin',
'capability_stealth',
'track_across',
'track_across_alias',
'track_crossdomain_linking',
'track_feed',
'track_feed_addcampaign',
'track_feed_campaign',
'cache',
'disable_timelimit',
'connection_timeout',
'disable_ssl_verify',
'disable_ssl_verify_host',
'piwik_useragent',
'piwik_useragent_string',
'track_datacfasync',
'track_cdnurl',
'track_cdnurlssl',
'force_protocol',
);
delete_option('wp-piwik-manually'); $settings = array(
delete_option('wp-piwik-notices'); 'name',
'site_id',
'noscript_code',
'tracking_code',
'last_tracking_code_update',
'dashboard_revision',
);
$wpdb->query("DELETE FROM $wpdb->postmeta WHERE meta_key LIKE 'wp-piwik-%'"); if ( function_exists( 'is_multisite' ) && is_multisite() ) {
$wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_wp-piwik_%'"); if ( isset( $limit ) && isset( $page ) ) {
$wpdb->query("DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_timeout_wp-piwik_%'"); $query_limit = 'LIMIT ' . (int) ( ( $page - 1 ) * $limit ) . ',' . (int) $limit . ' ';
}
// phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
$ary_blogs = $wpdb->get_results( $wpdb->prepare( 'SELECT blog_id FROM %s ' . $query_limit . 'ORDER BY blog_id', $wpdb->blogs ), ARRAY_A );
if ( is_array( $ary_blogs ) ) {
foreach ( $ary_blogs as $ary_blog ) {
foreach ( $settings as $key ) {
delete_blog_option( $ary_blog['blog_id'], 'wp-piwik-' . $key );
}
switch_to_blog( $ary_blog['blog_id'] );
$wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_key LIKE 'wp-piwik_%'" );
$wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_wp-piwik_%'" );
$wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_timeout_wp-piwik_%'" );
restore_current_blog();
}
}
foreach ( $global_settings as $key ) {
delete_site_option( 'wp-piwik_global-' . $key );
}
delete_site_option( 'wp-piwik-manually' );
delete_site_option( 'wp-piwik-notices' );
}
foreach ( $settings as $key ) {
delete_option( 'wp-piwik-' . $key );
}
foreach ( $global_settings as $key ) {
delete_option( 'wp-piwik_global-' . $key );
}
delete_option( 'wp-piwik-manually' );
delete_option( 'wp-piwik-notices' );
$wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_key LIKE 'wp-piwik-%'" );
$wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_wp-piwik_%'" );
$wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_timeout_wp-piwik_%'" );
}
wp_matomo_uninstall();

View File

@ -1,41 +1,55 @@
<?php <?php
/**
* @package wp-piwik
* phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
*/
// Get & delete old version's options // Get & delete old version's options
if (self::$settings->checkNetworkActivation ()) { if ( self::$settings->check_network_activation() ) {
$oldGlobalOptions = get_site_option ( 'wp-piwik_global-settings', array () ); $old_global_options = 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 () ); $old_global_options = 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 () ); $old_options = get_option( 'wp-piwik_settings', array() );
delete_option('wp-piwik_settings'); delete_option( 'wp-piwik_settings' );
if (self::$settings->checkNetworkActivation ()) { if ( self::$settings->check_network_activation() ) {
global $wpdb; global $wpdb;
$aryBlogs = \WP_Piwik\Settings::getBlogList(); $ary_blogs = \WP_Piwik\Settings::get_blog_list();
if (is_array($aryBlogs)) if ( is_array( $ary_blogs ) ) {
foreach ($aryBlogs as $aryBlog) { foreach ( $ary_blogs as $ary_blog ) {
$oldOptions = get_blog_option ( $aryBlog['blog_id'], 'wp-piwik_settings', array () ); $old_options = get_blog_option( $ary_blog['blog_id'], 'wp-piwik_settings', array() );
if (!$this->isConfigured()) if ( ! $this->is_configured() ) {
foreach ( $oldOptions as $key => $value ) foreach ( $old_options as $key => $value ) {
self::$settings->setOption ( $key, $value, $aryBlog['blog_id'] ); self::$settings->set_option( $key, $value, $ary_blog['blog_id'] );
delete_blog_option($aryBlog['blog_id'], 'wp-piwik_settings'); }
}
delete_blog_option( $ary_blog['blog_id'], 'wp-piwik_settings' );
} }
}
} }
if (!$this->isConfigured()) { if ( ! $this->is_configured() ) {
if (!$oldGlobalOptions['add_tracking_code']) $oldGlobalOptions['track_mode'] = 'disabled'; if ( ! $old_global_options['add_tracking_code'] ) {
elseif (!$oldGlobalOptions['track_mode']) $oldGlobalOptions['track_mode'] = 'default'; $old_global_options['track_mode'] = 'disabled';
elseif ($oldGlobalOptions['track_mode'] == 1) $oldGlobalOptions['track_mode'] = 'js'; } elseif ( ! $old_global_options['track_mode'] ) {
elseif ($oldGlobalOptions['track_mode'] == 2) $oldGlobalOptions['track_mode'] = 'proxy'; $old_global_options['track_mode'] = 'default';
} elseif ( 1 === (int) $old_global_options['track_mode'] ) {
$old_global_options['track_mode'] = 'js';
} elseif ( 2 === (int) $old_global_options['track_mode'] ) {
$old_global_options['track_mode'] = 'proxy';
}
// Store old values in new settings // Store old values in new settings
foreach ( $oldGlobalOptions as $key => $value ) foreach ( $old_global_options as $key => $value ) {
self::$settings->setGlobalOption ( $key, $value ); self::$settings->set_global_option( $key, $value );
foreach ( $oldOptions as $key => $value ) }
self::$settings->setOption ( $key, $value ); foreach ( $old_options as $key => $value ) {
self::$settings->set_option( $key, $value );
}
} }
self::$settings->save (); self::$settings->save();

View File

@ -1,13 +1,18 @@
<?php <?php
/**
* @package wp-piwik
* phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
*/
// Re-write Piwik Pro configuration to default http configuration // Re-write Piwik Pro configuration to default http configuration
if ($this->isConfigured() && self::$settings->getGlobalOption ( 'piwik_mode' ) == 'pro') { if ( $this->is_configured() && 'pro' === self::$settings->get_global_option( 'piwik_mode' ) ) {
self::$settings->setGlobalOption ( 'piwik_url', 'https://' . self::$settings->getGlobalOption ( 'piwik_user' ) . '.piwik.pro/'); self::$settings->set_global_option( 'piwik_url', 'https://' . self::$settings->get_global_option( 'piwik_user' ) . '.piwik.pro/' );
self::$settings->setGlobalOption ( 'piwik_mode', 'http' ); self::$settings->set_global_option( 'piwik_mode', 'http' );
} }
// If post annotations are already enabled, choose all existing post types // If post annotations are already enabled, choose all existing post types
if (self::$settings->getGlobalOption('add_post_annotations')) if ( self::$settings->get_global_option( 'add_post_annotations' ) ) {
self::$settings->setGlobalOption('add_post_annotations', get_post_types()); self::$settings->set_global_option( 'add_post_annotations', get_post_types() );
}
self::$settings->save (); self::$settings->save();

View File

@ -1,10 +1,14 @@
<?php <?php
/**
* @package wp-piwik
* phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
*/
// Set range for per post stats // Set range for per post stats
if (self::$settings->getGlobalOption('perpost_stats')) { if ( self::$settings->get_global_option( 'perpost_stats' ) ) {
self::$settings->setGlobalOption('perpost_stats', "last30"); self::$settings->set_global_option( 'perpost_stats', 'last30' );
} else { } else {
self::$settings->setGlobalOption('perpost_stats', "disabled"); self::$settings->set_global_option( 'perpost_stats', 'disabled' );
} }
self::$settings->save (); self::$settings->save();

View File

@ -1,4 +1,8 @@
<?php <?php
/**
* @package wp-piwik
* phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
*/
self::$settings->setGlobalOption('plugin_display_name', "Connect Matomo"); self::$settings->set_global_option( 'plugin_display_name', 'Connect Matomo' );
self::$settings->save (); self::$settings->save();

View File

@ -1,9 +1,16 @@
<?php <?php
$aryWPMUConfig = get_site_option ( 'wpmu-piwik_global-settings', false ); /**
if (self::$settings->checkNetworkActivation () && $aryWPMUConfig) { * @package wp-piwik
foreach ( $aryWPMUConfig as $key => $value ) * phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
self::$settings->setGlobalOption ( $key, $value ); */
delete_site_option ( 'wpmu-piwik_global-settings' );
self::$settings->setGlobalOption ( 'auto_site_config', true ); $ary_wpmu_config = get_site_option( 'wpmu-piwik_global-settings', false );
} else if ( self::$settings->check_network_activation() && $ary_wpmu_config ) {
self::$settings->setGlobalOption ( 'auto_site_config', false ); foreach ( $ary_wpmu_config as $key => $value ) {
self::$settings->set_global_option( $key, $value );
}
delete_site_option( 'wpmu-piwik_global-settings' );
self::$settings->set_global_option( 'auto_site_config', true );
} else {
self::$settings->set_global_option( 'auto_site_config', false );
}

View File

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

View File

@ -1,10 +1,16 @@
<?php <?php
$aryRemoveOptions = array ( /**
'wp-piwik_siteid', * @package wp-piwik
'wp-piwik_404', * phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
'wp-piwik_scriptupdate', */
'wp-piwik_dashboardid',
'wp-piwik_jscode' $ary_remove_options = array(
'wp-piwik_siteid',
'wp-piwik_404',
'wp-piwik_scriptupdate',
'wp-piwik_dashboardid',
'wp-piwik_jscode',
); );
foreach ( $aryRemoveOptions as $strRemoveOption ) foreach ( $ary_remove_options as $str_remove_option ) {
delete_option ( $strRemoveOption ); delete_option( $str_remove_option );
}

View File

@ -1,54 +1,44 @@
<?php <?php
/* /**
Plugin Name: Connect Matomo * Plugin Name: Connect Matomo
* 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.
* Version: 1.1.5
* Author: Matomo, Andr&eacute; Br&auml;kling
* Author URI: https://matomo.org
* Text Domain: wp-piwik
* Domain Path: /languages
*
* @link https://matomo.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
* @package wp-piwik
*/
Plugin URI: http://wordpress.org/extend/plugins/wp-piwik/ if ( ! function_exists( 'add_action' ) ) {
header( 'Status: 403 Forbidden' );
Description: Adds Matomo statistics to your WordPress dashboard and is also able to add the Matomo Tracking Code to your blog. header( 'HTTP/1.1 403 Forbidden' );
exit();
Version: 1.0.30
Author: Andr&eacute; Br&auml;kling
Author URI: https://www.braekling.de
Text Domain: wp-piwik
Domain Path: /languages
License: GPL3
******************************************************************************************
Copyright (C) 2009-today Andre Braekling (email: webmaster@braekling.de)
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
the Free Software Foundation, either version 3 of the License, or
at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*******************************************************************************************/
if (! function_exists ( 'add_action' )) {
header ( 'Status: 403 Forbidden' );
header ( 'HTTP/1.1 403 Forbidden' );
exit ();
} }
if (! defined ( 'NAMESPACE_SEPARATOR' )) // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound
define ( 'NAMESPACE_SEPARATOR', '\\' ); if ( ! defined( 'NAMESPACE_SEPARATOR' ) ) {
// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound
define( 'NAMESPACE_SEPARATOR', '\\' );
}
/** /**
* Define WP-Piwik autoloader * Define WP-Piwik autoloader
* *
* @param string $class * @param string $class_name
* class name * class name
*/ */
function wp_piwik_autoloader($class) { function wp_piwik_autoloader( $class_name ) {
if (substr ( $class, 0, 9 ) == 'WP_Piwik' . NAMESPACE_SEPARATOR) { if ( 'WP_Piwik' . NAMESPACE_SEPARATOR === substr( $class_name, 0, 9 ) ) {
$class = str_replace ( '.', '', str_replace ( NAMESPACE_SEPARATOR, DIRECTORY_SEPARATOR, substr ( $class, 9 ) ) ); $class_name = str_replace( '.', '', str_replace( NAMESPACE_SEPARATOR, DIRECTORY_SEPARATOR, substr( $class_name, 9 ) ) );
require_once ('classes' . DIRECTORY_SEPARATOR . 'WP_Piwik' . DIRECTORY_SEPARATOR . $class . '.php'); $file = 'classes' . DIRECTORY_SEPARATOR . 'WP_Piwik' . DIRECTORY_SEPARATOR . $class_name . '.php';
if ( is_file( __DIR__ . '/' . $file ) ) {
require_once $file;
}
} }
} }
@ -57,27 +47,31 @@ function wp_piwik_autoloader($class) {
*/ */
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( esc_html__( '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( __DIR__ ) . 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_FILE', __FILE__ );
require_once (WP_PIWIK_PATH . 'config.php'); define( 'WP_PIWIK_PATH', __DIR__ . DIRECTORY_SEPARATOR );
require_once (WP_PIWIK_PATH . 'classes' . DIRECTORY_SEPARATOR . 'WP_Piwik.php'); require_once WP_PIWIK_PATH . 'config.php';
spl_autoload_register ( 'wp_piwik_autoloader' ); require_once WP_PIWIK_PATH . 'classes' . DIRECTORY_SEPARATOR . 'WP_Piwik.php';
$GLOBALS ['wp-piwik_debug'] = false; spl_autoload_register( 'wp_piwik_autoloader' );
if (class_exists ( 'WP_Piwik' )) // phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
add_action( 'init', 'wp_piwik_loader' ); $GLOBALS['wp-piwik_debug'] = false;
if ( class_exists( 'WP_Piwik' ) ) {
add_action( 'setup_theme', 'wp_piwik_loader' );
}
} }
function wp_piwik_loader() { function wp_piwik_loader() {
$GLOBALS ['wp-piwik'] = new WP_Piwik (); // phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
$GLOBALS['wp-piwik'] = new WP_Piwik();
} }