Sync plugins from current page

Signed-off-by: Adrian Nöthlich <git@promasu.tech>
This commit is contained in:
2019-09-11 19:08:46 +02:00
parent 85d41e4216
commit 8515ff9587
1847 changed files with 505469 additions and 0 deletions

View File

@@ -0,0 +1,653 @@
<?php
/**
* Class WP_Statistics_Admin_Pages
*/
class WP_Statistics_Admin_Pages {
//Transient For Show Notice Setting
public static $setting_notice = '_show_notice_wp_statistics';
/**
* Load Overview Page
*/
static function overview() {
global $WP_Statistics;
// Right side "wide" widgets
if ( $WP_Statistics->get_option( 'visits' ) ) {
add_meta_box(
'wps_hits_postbox',
__( 'Hit Statistics', 'wp-statistics' ),
'wp_statistics_generate_overview_postbox_contents',
$WP_Statistics->menu_slugs['overview'],
'normal',
null,
array( 'widget' => 'hits' )
);
}
if ( $WP_Statistics->get_option( 'visitors' ) ) {
add_meta_box(
'wps_top_visitors_postbox',
__( 'Top Visitors', 'wp-statistics' ),
'wp_statistics_generate_overview_postbox_contents',
$WP_Statistics->menu_slugs['overview'],
'normal',
null,
array( 'widget' => 'top.visitors' )
);
add_meta_box(
'wps_search_postbox',
__( 'Search Engine Referrals', 'wp-statistics' ),
'wp_statistics_generate_overview_postbox_contents',
$WP_Statistics->menu_slugs['overview'],
'normal',
null,
array( 'widget' => 'search' )
);
add_meta_box(
'wps_words_postbox',
__( 'Latest Search Words', 'wp-statistics' ),
'wp_statistics_generate_overview_postbox_contents',
$WP_Statistics->menu_slugs['overview'],
'normal',
null,
array( 'widget' => 'words' )
);
add_meta_box(
'wps_recent_postbox',
__( 'Recent Visitors', 'wp-statistics' ),
'wp_statistics_generate_overview_postbox_contents',
$WP_Statistics->menu_slugs['overview'],
'normal',
null,
array( 'widget' => 'recent' )
);
if ( $WP_Statistics->get_option( 'geoip' ) ) {
add_meta_box(
'wps_map_postbox',
__( 'Today\'s Visitors Map', 'wp-statistics' ),
'wp_statistics_generate_overview_postbox_contents',
$WP_Statistics->menu_slugs['overview'],
'normal',
null,
array( 'widget' => 'map' )
);
}
}
if ( $WP_Statistics->get_option( 'pages' ) ) {
add_meta_box(
'wps_pages_postbox',
__( 'Top 10 Pages', 'wp-statistics' ),
'wp_statistics_generate_overview_postbox_contents',
$WP_Statistics->menu_slugs['overview'],
'normal',
null,
array( 'widget' => 'pages' )
);
}
// Left side "thin" widgets.
if ( $WP_Statistics->get_option( 'visitors' ) ) {
add_meta_box(
'wps_summary_postbox',
__( 'Summary', 'wp-statistics' ),
'wp_statistics_generate_overview_postbox_contents',
$WP_Statistics->menu_slugs['overview'],
'side',
null,
array( 'widget' => 'summary' )
);
add_meta_box(
'wps_browsers_postbox',
__( 'Browsers', 'wp-statistics' ),
'wp_statistics_generate_overview_postbox_contents',
$WP_Statistics->menu_slugs['overview'],
'side',
null,
array( 'widget' => 'browsers' )
);
add_meta_box(
'wps_referring_postbox',
__( 'Top Referring Sites', 'wp-statistics' ),
'wp_statistics_generate_overview_postbox_contents',
$WP_Statistics->menu_slugs['overview'],
'side',
null,
array( 'widget' => 'referring' )
);
if ( $WP_Statistics->get_option( 'geoip' ) ) {
add_meta_box(
'wps_countries_postbox',
__( 'Top 10 Countries', 'wp-statistics' ),
'wp_statistics_generate_overview_postbox_contents',
$WP_Statistics->menu_slugs['overview'],
'side',
null,
array( 'widget' => 'countries' )
);
}
}
//Left Show User online table
if ( $WP_Statistics->get_option( 'useronline' ) ) {
add_meta_box( 'wps_users_online_postbox', __( 'Online Users', 'wp-statistics' ), 'wp_statistics_generate_overview_postbox_contents', $WP_Statistics->menu_slugs['overview'], 'side', null, array( 'widget' => 'users_online' ) );
}
}
/**
* Check in admin page
*
* @param $page | For Get List @see \WP_STATISTICS\WP_Statistics::$page
* @return bool
*/
public static function in_page( $page ) {
global $pagenow;
//Check is custom page
if ( $pagenow == "admin.php" and isset( $_REQUEST['page'] ) and $_REQUEST['page'] == WP_Statistics::$page[ $page ] ) {
return true;
}
return false;
}
/**
* Show Page title
* @param string $title
*/
public static function show_page_title( $title = '' ) {
//Check if $title not Set
if ( empty( $title ) and function_exists( 'get_admin_page_title' ) ) {
$title = get_admin_page_title();
}
//show Page title
echo '<img src="' . plugins_url( 'wp-statistics/assets/images/' ) . '/title-logo.png" class="wps_page_title"><h2 class="wps_title">' . $title . '</h2>';
//do_action after wp_statistics
do_action( 'wp_statistics_after_title' );
}
/**
* Get Admin Url
*
* @param null $page
* @param array $arg
* @area is_admin
* @return string
*/
public static function admin_url( $page = null, $arg = array() ) {
//Check If Pages is in Wp-statistics
if ( array_key_exists( $page, WP_Statistics::$page ) ) {
$page = WP_Statistics::$page[ $page ];
}
return add_query_arg( array_merge( array( 'page' => $page ), $arg ), admin_url( 'admin.php' ) );
}
/**
* Show MetaBox button Refresh/Direct Button Link in Top of Meta Box
*
* @param string $export
* @return string
*/
public static function meta_box_button( $export = 'all' ) {
//Prepare button
$refresh = '</button><button class="handlediv button-link wps-refresh" type="button" id="{{refreshid}}">' . wp_statistics_icons( 'dashicons-update' ) . '<span class="screen-reader-text">' . __( 'Reload', 'wp-statistics' ) . '</span></button>';
$more = '<button class="handlediv button-link wps-more" type="button" id="{{moreid}}">' . wp_statistics_icons( 'dashicons-external' ) . '<span class="screen-reader-text">' . __( 'More Details', 'wp-statistics' ) . '</span></button>';
//Export
if ( $export == 'all' ) {
return $refresh . $more;
} else {
return $$export;
}
}
/**
* Show Loading Meta Box
*/
public static function loading_meta_box() {
$loading = '<div class="wps_loading_box"><img src=" ' . plugins_url( 'wp-statistics/assets/images/' ) . 'loading.svg" alt="' . __( 'Reloading...', 'wp-statistics' ) . '"></div>';
return $loading;
}
/**
* Sanitize Email Subject
*
* @param $subject
* @return string|string[]|null
*/
public static function sanitize_mail_subject( $subject ) {
# Remove Special character
$str = preg_replace( '/[\'^£$%&*()}{@#~?><>,|=+¬]/', '', $subject );
# Replace sequences of spaces with hyphen
$str = preg_replace( '/ */', '-', $str );
# You may also want to try this alternative:
$str = preg_replace( '/\\s+/', ' ', $str );
return $str;
}
/**
* Plugins
*/
static function plugins() {
// Activate or deactivate the selected plugin
if ( isset( $_GET['action'] ) ) {
if ( $_GET['action'] == 'activate' ) {
$result = activate_plugin( $_GET['plugin'] . '/' . $_GET['plugin'] . '.php' );
if ( is_wp_error( $result ) ) {
wp_statistics_admin_notice_result( 'error', $result->get_error_message() );
} else {
wp_statistics_admin_notice_result( 'success', __( 'Add-On activated.', 'wp-statistics' ) );
}
}
if ( $_GET['action'] == 'deactivate' ) {
$result = deactivate_plugins( $_GET['plugin'] . '/' . $_GET['plugin'] . '.php' );
if ( is_wp_error( $result ) ) {
wp_statistics_admin_notice_result( 'error', $result->get_error_message() );
} else {
wp_statistics_admin_notice_result( 'success', __( 'Add-On deactivated.', 'wp-statistics' ) );
}
}
}
$response = wp_remote_get( 'https://wp-statistics.com/wp-json/plugin/addons' );
$response_code = wp_remote_retrieve_response_code( $response );
$error = null;
$plugins = array();
// Check response
if ( is_wp_error( $response ) ) {
$error = $response->get_error_message();
} else {
if ( $response_code == '200' ) {
$plugins = json_decode( $response['body'] );
} else {
$error = $response['body'];
}
}
include WP_Statistics::$reg['plugin-dir'] . 'includes/templates/plugins.php';
}
/**
* Donate
*/
static function donate() {
echo "<script>window.location.href='http://wp-statistics.com/donate';</script>";
}
/**
* Loads the optimization page code.
*/
static function optimization() {
global $wpdb, $WP_Statistics;
// Check the current user has the rights to be here.
if ( ! current_user_can( wp_statistics_validate_capability( $WP_Statistics->get_option( 'manage_capability', 'manage_options' ) ) ) ) {
wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
}
// When we create $WP_Statistics the user has not been authenticated yet so we cannot load the user preferences
// during the creation of the class. Instead load them now that the user exists.
$WP_Statistics->load_user_options();
// Get the row count for each of the tables, we'll use this later on in the wps_optimization.php file.
$list_table = wp_statistics_db_table( 'all' );
$result = array();
foreach ( $list_table as $tbl_key => $tbl_name ) {
$result[ $tbl_name ] = $wpdb->get_var( "SELECT COUNT(*) FROM `$tbl_name`" );
}
include WP_Statistics::$reg['plugin-dir'] . "includes/optimization/wps-optimization.php";
}
/**
* This function displays the HTML for the settings page.
*/
static function settings() {
global $WP_Statistics;
// Check the current user has the rights to be here.
if ( ! current_user_can( wp_statistics_validate_capability( $WP_Statistics->get_option( 'read_capability', 'manage_options' ) ) ) ) {
wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
}
// When we create $WP_Statistics the user has not been authenticated yet so we cannot load the user preferences
// during the creation of the class. Instead load them now that the user exists.
$WP_Statistics->load_user_options();
// Check admin notices.
if ( $WP_Statistics->get_option( 'admin_notices' ) == true ) {
$WP_Statistics->update_option( 'disable_donation_nag', false );
$WP_Statistics->update_option( 'disable_suggestion_nag', false );
}
include WP_Statistics::$reg['plugin-dir'] . "includes/settings/wps-settings.php";
// We could let the download happen at the end of the page, but this way we get to give some
// feedback to the users about the result.
if ( $WP_Statistics->get_option( 'geoip' ) and isset( $_POST['update_geoip'] ) and isset( $_POST['geoip_name'] ) ) {
//Check Geo ip Exist in Database
if ( isset( WP_Statistics_Updates::$geoip[ $_POST['geoip_name'] ] ) ) {
$result = WP_Statistics_Updates::download_geoip( $_POST['geoip_name'], "update" );
if ( isset( $result['status'] ) and $result['status'] === false ) {
add_filter( "wp_statistics_redirect_setting", function ( $redirect ) {
$redirect = true;
return $redirect;
} );
} else {
echo $result['notice'];
}
}
}
//Enabled Geo ip Country Or City And download
foreach ( array( "geoip" => "country", "geoip_city" => "city" ) as $geo_opt => $geo_name ) {
if ( ! isset( $_POST['update_geoip'] ) and isset( $_POST[ 'wps_' . $geo_opt ] ) ) {
//Check File Not Exist
$upload_dir = wp_upload_dir();
$file = $upload_dir['basedir'] . '/wp-statistics/' . WP_Statistics_Updates::$geoip[ $geo_name ]['file'] . '.mmdb';
if ( ! file_exists( $file ) ) {
$result = WP_Statistics_Updates::download_geoip( $geo_name );
if ( isset( $result['status'] ) and $result['status'] === false ) {
add_filter( "wp_statistics_redirect_setting", function ( $redirect ) {
$redirect = true;
return $redirect;
} );
} else {
echo $result['notice'];
}
}
}
}
//Redirect Set Setting
self::wp_statistics_redirect_setting();
}
/**
* Set Transient Notice
*
* @param $text
* @param string $type
*/
public static function set_admin_notice( $text, $type = 'error' ) {
$get = get_transient( WP_Statistics_Admin_Pages::$setting_notice );
if ( $get != false ) {
$results = $get;
}
delete_transient( WP_Statistics_Admin_Pages::$setting_notice );
$results[] = array( "text" => $text, "type" => $type );
set_transient( WP_Statistics_Admin_Pages::$setting_notice, $results, 1 * HOUR_IN_SECONDS );
}
/**
* Notification Setting
*/
public static function wp_statistics_notice_setting() {
global $pagenow, $WP_Statistics;
//Show Notice By Plugin
$get = get_transient( WP_Statistics_Admin_Pages::$setting_notice );
if ( $get != false ) {
foreach ( $get as $item ) {
wp_statistics_admin_notice_result( $item['type'], $item['text'] );
}
delete_transient( WP_Statistics_Admin_Pages::$setting_notice );
}
//Check referring Spam Update
if ( $pagenow == "admin.php" and isset( $_GET['page'] ) and $_GET['page'] == WP_Statistics::$page['settings'] and isset( $_GET['update-referrerspam'] ) ) {
// Update referrer spam
$update_spam = WP_Statistics_Updates::download_referrerspam();
if ( $update_spam === true ) {
wp_statistics_admin_notice_result( 'success', __( 'Updated Matomo Referrer Spam.', 'wp-statistics' ) );
} else {
wp_statistics_admin_notice_result( 'error', __( 'error in get referrer spam list. please try again.', 'wp-statistics' ) );
}
}
}
/**
* Redirect Jquery
* @param bool $redirect
*/
public static function wp_statistics_redirect_setting( $redirect = false ) {
$redirect = apply_filters( 'wp_statistics_redirect_setting', $redirect );
if ( $redirect === true ) {
echo '<script>window.location.replace("' . ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] === 'on' ? "https" : "http" ) . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]" . '");</script>';
}
}
/**
* @param string $log_type Log Type
*/
static function log( $log_type = "" ) {
global $wpdb, $WP_Statistics, $plugin_page;
switch ( $plugin_page ) {
case WP_Statistics::$page['browser']:
$log_type = 'all-browsers';
break;
case WP_Statistics::$page['countries']:
$log_type = 'top-countries';
break;
case WP_Statistics::$page['exclusions']:
$log_type = 'exclusions';
break;
case WP_Statistics::$page['hits']:
$log_type = 'hit-statistics';
break;
case WP_Statistics::$page['online']:
$log_type = 'online';
break;
case WP_Statistics::$page['pages']:
$log_type = 'top-pages';
break;
case WP_Statistics::$page['categories']:
$log_type = 'categories';
break;
case WP_Statistics::$page['tags']:
$log_type = 'tags';
break;
case WP_Statistics::$page['authors']:
$log_type = 'authors';
break;
case WP_Statistics::$page['referrers']:
$log_type = 'top-referring-site';
break;
case WP_Statistics::$page['searches']:
$log_type = 'search-statistics';
break;
case WP_Statistics::$page['words']:
$log_type = 'last-all-search';
break;
case WP_Statistics::$page['top-visitors']:
$log_type = 'top-visitors';
break;
case WP_Statistics::$page['visitors']:
$log_type = 'last-all-visitor';
break;
default:
$log_type = "";
}
// When we create $WP_Statistics the user has not been authenticated yet so we cannot load the user preferences
// during the creation of the class. Instead load them now that the user exists.
$WP_Statistics->load_user_options();
// We allow for a get style variable to be passed to define which function to use.
if ( $log_type == "" && array_key_exists( 'type', $_GET ) ) {
$log_type = $_GET['type'];
}
// Verify the user has the rights to see the statistics.
if ( ! current_user_can(
wp_statistics_validate_capability(
$WP_Statistics->get_option(
'read_capability',
'manage_option'
)
)
)
) {
wp_die( __( 'You do not have sufficient permissions to access this page.' ) );
}
// We want to make sure the tables actually exist before we blindly start access them.
$result = $wpdb->query(
"SHOW TABLES WHERE `Tables_in_{$wpdb->dbname}` = '{$wpdb->prefix}statistics_visitor' OR `Tables_in_{$wpdb->dbname}` = '{$wpdb->prefix}statistics_visit' OR `Tables_in_{$wpdb->dbname}` = '{$wpdb->prefix}statistics_exclusions' OR `Tables_in_{$wpdb->dbname}` = '{$wpdb->prefix}statistics_historical' OR `Tables_in_{$wpdb->dbname}` = '{$wpdb->prefix}statistics_pages' OR `Tables_in_{$wpdb->dbname}` = '{$wpdb->prefix}statistics_useronline' OR `Tables_in_{$wpdb->dbname}` = '{$wpdb->prefix}statistics_search'"
);
if ( $result != 7 ) {
$get_bloginfo_url = WP_Statistics_Admin_Pages::admin_url( 'optimization', array( 'tab' => 'database' ) );
$missing_tables = array();
$result = $wpdb->query(
"SHOW TABLES WHERE `Tables_in_{$wpdb->dbname}` = '{$wpdb->prefix}statistics_visitor'"
);
if ( $result != 1 ) {
$missing_tables[] = $wpdb->prefix . 'statistics_visitor';
}
$result = $wpdb->query( "SHOW TABLES WHERE `Tables_in_{$wpdb->dbname}` = '{$wpdb->prefix}statistics_visit'" );
if ( $result != 1 ) {
$missing_tables[] = $wpdb->prefix . 'statistics_visit';
}
$result = $wpdb->query(
"SHOW TABLES WHERE `Tables_in_{$wpdb->dbname}` = '{$wpdb->prefix}statistics_exclusions'"
);
if ( $result != 1 ) {
$missing_tables[] = $wpdb->prefix . 'statistics_exclusions';
}
$result = $wpdb->query(
"SHOW TABLES WHERE `Tables_in_{$wpdb->dbname}` = '{$wpdb->prefix}statistics_historical'"
);
if ( $result != 1 ) {
$missing_tables[] = $wpdb->prefix . 'statistics_historical';
}
$result = $wpdb->query(
"SHOW TABLES WHERE `Tables_in_{$wpdb->dbname}` = '{$wpdb->prefix}statistics_useronline'"
);
if ( $result != 1 ) {
$missing_tables[] = $wpdb->prefix . 'statistics_useronline';
}
$result = $wpdb->query( "SHOW TABLES WHERE `Tables_in_{$wpdb->dbname}` = '{$wpdb->prefix}statistics_pages'" );
if ( $result != 1 ) {
$missing_tables[] = $wpdb->prefix . 'statistics_pages';
}
$result = $wpdb->query(
"SHOW TABLES WHERE `Tables_in_{$wpdb->dbname}` = '{$wpdb->prefix}statistics_search'"
);
if ( $result != 1 ) {
$missing_tables[] = $wpdb->prefix . 'statistics_search';
}
wp_die(
'<div class="error"><p>' . sprintf(
__(
'The following plugin table(s) do not exist in the database, please re-run the %s install routine %s:',
'wp-statistics'
),
'<a href="' . $get_bloginfo_url . '">',
'</a>'
) . implode( ', ', $missing_tables ) . '</p></div>'
);
}
// Load the postbox script that provides the widget style boxes.
wp_enqueue_script( 'common' );
wp_enqueue_script( 'wp-lists' );
wp_enqueue_script( 'postbox' );
// Load the css we use for the statistics pages.
wp_enqueue_style( 'wpstatistics-log-css', WP_Statistics::$reg['plugin-url'] . 'assets/css/log.css', true, WP_Statistics::$reg['version'] );
wp_enqueue_style( 'wpstatistics-pagination-css', WP_Statistics::$reg['plugin-url'] . 'assets/css/pagination.css', true, WP_Statistics::$reg['version'] );
// The different pages have different files to load.
switch ( $log_type ) {
case 'all-browsers':
case 'top-countries':
case 'hit-statistics':
case 'search-statistics':
case 'exclusions':
case 'online':
case 'top-visitors':
case 'categories':
case 'tags':
case 'authors':
include WP_Statistics::$reg['plugin-dir'] . 'includes/log/' . $log_type . '.php';
break;
case 'last-all-search':
include WP_Statistics::$reg['plugin-dir'] . 'includes/log/last-search.php';
break;
case 'last-all-visitor':
include WP_Statistics::$reg['plugin-dir'] . 'includes/log/last-visitor.php';
break;
case 'top-referring-site':
include WP_Statistics::$reg['plugin-dir'] . 'includes/log/top-referring.php';
break;
case 'top-pages':
// If we've been given a page id or uri to get statistics for, load the page stats, otherwise load the page stats overview page.
if ( array_key_exists( 'page-id', $_GET ) || array_key_exists( 'page-uri', $_GET ) || array_key_exists( 'prepage', $_GET ) ) {
include WP_Statistics::$reg['plugin-dir'] . 'includes/log/page-statistics.php';
} else {
include WP_Statistics::$reg['plugin-dir'] . 'includes/log/top-pages.php';
}
break;
default:
if ( get_current_screen()->parent_base == WP_Statistics::$page['overview'] ) {
wp_enqueue_style( 'wpstatistics-jqvmap-css', WP_Statistics::$reg['plugin-url'] . 'assets/jqvmap/jqvmap.css', true, '1.5.1' );
wp_enqueue_script( 'wpstatistics-jquery-vmap', WP_Statistics::$reg['plugin-url'] . 'assets/jqvmap/jquery.vmap.js', true, '1.5.1' );
wp_enqueue_script( 'wpstatistics-jquery-vmap-world', WP_Statistics::$reg['plugin-url'] . 'assets/jqvmap/maps/jquery.vmap.world.js', true, '1.5.1' );
// Load our custom widgets handling javascript.
wp_enqueue_script( 'wp_statistics_log', WP_Statistics::$reg['plugin-url'] . 'assets/js/log.js' );
include WP_Statistics::$reg['plugin-dir'] . 'includes/log/log.php';
}
break;
}
}
}

View File

@@ -0,0 +1,702 @@
<?php
/**
* Class WP_Statistics_Admin
*/
class WP_Statistics_Admin {
/**
* WP_Statistics_Admin constructor.
*/
public function __construct() {
global $WP_Statistics;
// Check to see if we're installed and are the current version.
WP_Statistics::$installed_version = get_option( 'wp_statistics_plugin_version' );
if ( WP_Statistics::$installed_version != WP_Statistics::$reg['version'] ) {
new WP_Statistics_Install;
}
// If we've been flagged to remove all of the data, then do so now.
if ( get_option( 'wp_statistics_removal' ) == 'true' ) {
new WP_Statistics_Uninstall;
}
// If we've been removed, return without doing anything else.
if ( get_option( 'wp_statistics_removal' ) == 'done' ) {
add_action( 'admin_notices', array( $this, 'removal_admin_notice' ), 10, 2 );
return;
}
//Show Admin Menu
add_action( 'admin_menu', array( $this, 'menu' ) );
if ( is_multisite() ) {
add_action( 'network_admin_menu', 'WP_Statistics_Network_Admin::menu' );
}
//Load Script in Admin Area
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
//init Export Class
new WP_Statistics_Export;
//init Ajax Class
new WP_Statistics_Ajax;
//init Dashboard Widget
new WP_Statistics_Dashboard;
//Add Custom MetaBox in Wp-statistics Admin Page
add_action( 'add_meta_boxes', 'WP_Statistics_Editor::add_meta_box' );
// Display the admin notices if we should.
if ( isset( $pagenow ) && array_key_exists( 'page', $_GET ) ) {
if ( $pagenow == "admin.php" && substr( $_GET['page'], 0, 14 ) == 'wp-statistics/' ) {
add_action( 'admin_notices', array( $this, 'not_enable' ) );
}
}
//Change Plugin Action link in Plugin.php admin
add_filter( 'plugin_action_links_' . plugin_basename( WP_Statistics::$reg['main-file'] ), array( $this, 'settings_links' ), 10, 2 );
add_filter( 'plugin_row_meta', array( $this, 'add_meta_links' ), 10, 2 );
//Add Column in Post Type Wp_List Table
add_action( 'load-edit.php', array( $this, 'load_edit_init' ) );
if ( $WP_Statistics->get_option( 'pages' ) && $WP_Statistics->get_option( 'hit_post_metabox' ) ) {
add_action( 'post_submitbox_misc_actions', array( $this, 'post_init' ) );
}
//init ShortCode
add_action( 'admin_init', 'WP_Statistics_Shortcode::shortcake' );
// WP-Statistics welcome page hooks
add_action( 'admin_menu', 'WP_Statistics_Welcome::menu' );
add_action( 'upgrader_process_complete', 'WP_Statistics_Welcome::do_welcome', 10, 2 );
add_action( 'admin_init', 'WP_Statistics_Welcome::init' );
// Runs some scripts at the end of the admin panel inside the body tag
add_action( 'admin_footer', array( $this, 'admin_footer_scripts' ) );
// Load TinyMce Function
new WP_Statistics_TinyMCE;
// Add Notice Use cache plugin
add_action( 'admin_notices', array( $this, 'notification_use_cache_plugin' ) );
//Admin Notice Setting
add_action( 'admin_notices', 'WP_Statistics_Admin_Pages::wp_statistics_notice_setting' );
//Add Visitors Log Table
add_action( 'admin_init', array( $this, 'register_visitors_log_tbl' ) );
// Add Overview Ads
add_action( 'load-toplevel_page_' . WP_Statistics::$page['overview'], array( $this, 'overview_page_ads' ) );
//Check Require update page type in database
WP_Statistics_Install::_init_page_type_updater();
}
/**
* Create a New Table Visitors Log in mysql
*/
public function register_visitors_log_tbl() {
//Add Visitor RelationShip Table
if ( WP_Statistics_Admin_Pages::in_page( 'settings' ) and isset( $_POST['wps_visitors_log'] ) and $_POST['wps_visitors_log'] == 1 ) {
WP_Statistics_Install::setup_visitor_relationship_table();
}
}
/**
* This adds a row after WP Statistics in the plugin page
* IF we've been removed via the settings page.
*/
public function removal_admin_notice() {
$screen = get_current_screen();
if ( 'plugins' !== $screen->id ) {
return;
}
?>
<div class="error">
<p style="max-width:800px;"><?php
echo '<p>' . __( 'WP Statistics has been removed, please disable and delete it.', 'wp-statistics' ) . '</p>';
?></p>
</div>
<?php
}
/**
* OverView Page Ads
*/
public function overview_page_ads() {
// Get Overview Ads
$get_overview_ads = get_option( 'wp_statistics_overview_page_ads', false );
// Check Expire or not exist
if ( $get_overview_ads === false || ( is_array( $get_overview_ads ) and ( current_time( 'timestamp' ) >= ( $get_overview_ads['timestamp'] + WEEK_IN_SECONDS ) ) ) ) {
// Check Exist
$overview_ads = ( $get_overview_ads === false ? array() : $get_overview_ads );
// Get New Ads from API
$request = wp_remote_get( 'https://wp-statistics.com/wp-json/ads/overview', array( 'timeout' => 30 ) );
if ( is_wp_error( $request ) ) {
return;
}
// Get Json Data
$data = json_decode( wp_remote_retrieve_body( $request ), true );
// Set new Timestamp
$overview_ads['timestamp'] = current_time( 'timestamp' );
// Set Ads
$overview_ads['ads'] = ( empty( $data ) ? array( 'status' => 'no', 'ID' => 'none' ) : $data );
// Set Last Viewed
$overview_ads['view'] = ( isset( $get_overview_ads['view'] ) ? $get_overview_ads['view'] : '' );
// Set Option
update_option( 'wp_statistics_overview_page_ads', $overview_ads, 'no' );
}
}
/**
* This function outputs error messages in the admin interface
* if the primary components of WP Statistics are enabled.
*/
public function not_enable() {
global $WP_Statistics;
// If the user had told us to be quite, do so.
if ( ! $WP_Statistics->get_option( 'hide_notices' ) ) {
// Check to make sure the current user can manage WP Statistics,
// if not there's no point displaying the warnings.
$manage_cap = wp_statistics_validate_capability(
$WP_Statistics->get_option(
'manage_capability',
'manage_options'
)
);
if ( ! current_user_can( $manage_cap ) ) {
return;
}
$get_bloginfo_url = WP_Statistics_Admin_Pages::admin_url( 'settings' );
$itemstoenable = array();
if ( ! $WP_Statistics->get_option( 'useronline' ) ) {
$itemstoenable[] = __( 'online user tracking', 'wp-statistics' );
}
if ( ! $WP_Statistics->get_option( 'visits' ) ) {
$itemstoenable[] = __( 'hit tracking', 'wp-statistics' );
}
if ( ! $WP_Statistics->get_option( 'visitors' ) ) {
$itemstoenable[] = __( 'visitor tracking', 'wp-statistics' );
}
if ( ! $WP_Statistics->get_option( 'geoip' ) && wp_statistics_geoip_supported() ) {
$itemstoenable[] = __( 'geoip collection', 'wp-statistics' );
}
if ( count( $itemstoenable ) > 0 ) {
echo '<div class="update-nag">' . sprintf( __( 'The following features are disabled, please go to %ssettings page%s and enable them: %s', 'wp-statistics' ), '<a href="' . $get_bloginfo_url . '">', '</a>', implode( __( ',', 'wp-statistics' ), $itemstoenable ) ) . '</div>';
}
$get_bloginfo_url = WP_Statistics_Admin_Pages::admin_url( 'optimization', array( 'tab' => 'database' ) );
$dbupdatestodo = array();
if ( ! $WP_Statistics->get_option( 'search_converted' ) ) {
$dbupdatestodo[] = __( 'search table', 'wp-statistics' );
}
// Check to see if there are any database changes the user hasn't done yet.
$dbupdates = $WP_Statistics->get_option( 'pending_db_updates', false );
// The database updates are stored in an array so loop thorugh it and output some notices.
if ( is_array( $dbupdates ) ) {
$dbstrings = array(
'date_ip_agent' => __( 'countries database index', 'wp-statistics' ),
'unique_date' => __( 'visit database index', 'wp-statistics' ),
);
foreach ( $dbupdates as $key => $update ) {
if ( $update == true ) {
$dbupdatestodo[] = $dbstrings[ $key ];
}
}
if ( count( $dbupdatestodo ) > 0 ) {
echo '<div class="update-nag">' . sprintf( __( 'Database updates are required, please go to %soptimization page%s and update the following: %s', 'wp-statistics' ), '<a href="' . $get_bloginfo_url . '">', '</a>', implode( __( ',', 'wp-statistics' ), $dbupdatestodo ) ) . '</div>';
}
}
}
}
/*
* Check User Active A cache Plugin in Wordpress
*/
static public function user_is_use_cache_plugin() {
$use = array( 'status' => false, 'plugin' => '' );
/* Wordpress core */
if ( defined( 'WP_CACHE' ) && WP_CACHE ) {
return array( 'status' => true, 'plugin' => 'core' );
}
/* WP Rocket */
if ( function_exists( 'get_rocket_cdn_url' ) ) {
return array( 'status' => true, 'plugin' => 'WP Rocket' );
}
/* WP Super Cache */
if ( function_exists( 'wpsc_init' ) ) {
return array( 'status' => true, 'plugin' => 'WP Super Cache' );
}
/* Comet Cache */
if ( function_exists( '___wp_php_rv_initialize' ) ) {
return array( 'status' => true, 'plugin' => 'Comet Cache' );
}
/* WP Fastest Cache */
if ( class_exists( 'WpFastestCache' ) ) {
return array( 'status' => true, 'plugin' => 'WP Fastest Cache' );
}
/* Cache Enabler */
if ( defined( 'CE_MIN_WP' ) ) {
return array( 'status' => true, 'plugin' => 'Cache Enabler' );
}
/* W3 Total Cache */
if ( defined( 'W3TC' ) ) {
return array( 'status' => true, 'plugin' => 'W3 Total Cache' );
}
return $use;
}
/*
* Show Notification Cache Plugin
*/
static public function notification_use_cache_plugin() {
global $WP_Statistics;
$screen = get_current_screen();
if ( $screen->id == "toplevel_page_" . WP_Statistics::$page['overview'] or $screen->id == "statistics_page_" . WP_Statistics::$page['settings'] ) {
$plugin = self::user_is_use_cache_plugin();
if ( ! $WP_Statistics->get_option( 'use_cache_plugin' ) and $plugin['status'] === true ) {
echo '<div class="notice notice-warning is-dismissible"><p>';
$alert = sprintf( __( 'You Are Using %s Plugin in WordPress', 'wp-statistics' ), $plugin['plugin'] );
if ( $plugin['plugin'] == "core" ) {
$alert = __( 'WP_CACHE is Enable in Your WordPress', 'wp-statistics' );
}
echo $alert . ", " . sprintf( __( 'Please enable %1$sCache Setting%2$s in WP Statistics.', 'wp-statistics' ), '<a href="' . WP_Statistics_Admin_Pages::admin_url( 'settings' ) . '">', '</a>' );
echo '</p></div>';
}
}
// Test Rest Api is Active for Cache
if ( $WP_Statistics->use_cache and $screen->id == "statistics_page_" . WP_Statistics::$page['settings'] ) {
if ( false === ( $check_rest_api = get_transient( '_check_rest_api_wp_statistics' ) ) ) {
$set_transient = true;
$alert = '<div class="notice notice-warning is-dismissible"><p>' . sprintf( __( 'Here is an error associated with Connecting WordPress Rest API, Please Flushing rewrite rules or activate wp rest api for performance WP-Statistics Plugin Cache / Go %1$sSettings->Permalinks%2$s', 'wp-statistics' ), '<a href="' . esc_url( admin_url( 'options-permalink.php' ) ) . '">', '</a>' ) . '</div>';
$request = wp_remote_post( path_join( get_rest_url(), WP_Statistics_Rest::route . '/' . WP_Statistics_Rest::func ), array(
'method' => 'POST',
'body' => array( 'rest-api-wp-statistics' => 'wp-statistics' )
) );
if ( is_wp_error( $request ) ) {
echo $alert;
$set_transient = false;
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body, true );
if ( ! isset( $data['rest-api-wp-statistics'] ) and $set_transient === true ) {
echo $alert;
$set_transient = false;
}
if ( $set_transient === true ) {
set_transient( '_check_rest_api_wp_statistics', array( "rest-api-wp-statistics" => "OK" ), 2 * HOUR_IN_SECONDS );
}
}
}
}
/**
* Add a settings link to the plugin list.
*
* @param string $links Links
* @param string $file Not Used!
*
* @return string Links
*/
public function settings_links( $links, $file ) {
global $WP_Statistics;
$manage_cap = wp_statistics_validate_capability( $WP_Statistics->get_option( 'manage_capability', 'manage_options' ) );
if ( current_user_can( $manage_cap ) ) {
array_unshift( $links, '<a href="' . WP_Statistics_Admin_Pages::admin_url( 'settings' ) . '">' . __( 'Settings', 'wp-statistics' ) . '</a>' );
}
return $links;
}
/**
* Add a WordPress plugin page and rating links to the meta information to the plugin list.
*
* @param string $links Links
* @param string $file File
*
* @return array Links
*/
public function add_meta_links( $links, $file ) {
if ( $file == plugin_basename( WP_Statistics::$reg['main-file'] ) ) {
$plugin_url = 'http://wordpress.org/plugins/wp-statistics/';
$links[] = '<a href="' . $plugin_url . '" target="_blank" title="' . __( 'Click here to visit the plugin on WordPress.org', 'wp-statistics' ) . '">' . __( 'Visit WordPress.org page', 'wp-statistics' ) . '</a>';
$rate_url = 'https://wordpress.org/support/plugin/wp-statistics/reviews/?rate=5#new-post';
$links[] = '<a href="' . $rate_url . '" target="_blank" title="' . __( 'Click here to rate and review this plugin on WordPress.org', 'wp-statistics' ) . '">' . __( 'Rate this plugin', 'wp-statistics' ) . '</a>';
}
return $links;
}
/**
* Call the add/render functions at the appropriate times.
*/
public function load_edit_init() {
global $WP_Statistics;
$read_cap = wp_statistics_validate_capability( $WP_Statistics->get_option( 'read_capability', 'manage_options' ) );
if ( current_user_can( $read_cap ) && $WP_Statistics->get_option( 'pages' ) && ! $WP_Statistics->get_option( 'disable_column' ) ) {
$post_types = WP_Statistics_Editor::get_list_post_type();
foreach ( $post_types as $type ) {
add_action( 'manage_' . $type . '_posts_columns', 'WP_Statistics_Admin::add_column', 10, 2 );
add_action( 'manage_' . $type . '_posts_custom_column', 'WP_Statistics_Admin::render_column', 10, 2 );
}
}
}
/**
* Add a custom column to post/pages for hit statistics.
*
* @param array $columns Columns
*
* @return array Columns
*/
static function add_column( $columns ) {
$columns['wp-statistics'] = __( 'Hits', 'wp-statistics' );
return $columns;
}
/**
* Render the custom column on the post/pages lists.
*
* @param string $column_name Column Name
* @param string $post_id Post ID
*/
static function render_column( $column_name, $post_id ) {
if ( $column_name == 'wp-statistics' ) {
echo "<a href='" . WP_Statistics_Admin_Pages::admin_url( 'pages', array( 'page-id' => $post_id ) ) . "'>" . wp_statistics_pages( 'total', "", $post_id ) . "</a>";
}
}
/**
* Add the hit count to the publish widget in the post/pages editor.
*/
public function post_init() {
global $post;
$id = $post->ID;
echo "<div class='misc-pub-section'>" . __( 'WP Statistics - Hits', 'wp-statistics' ) . ": <b><a href='" . WP_Statistics_Admin_Pages::admin_url( 'pages', array( 'page-id' => $id ) ) . "'>" . wp_statistics_pages( 'total', "", $id ) . "</a></b></div>";
}
/**
* This function adds the primary menu to WordPress.
*/
public function menu() {
global $WP_Statistics;
// Get the read/write capabilities required to view/manage the plugin as set by the user.
$read_cap = wp_statistics_validate_capability( $WP_Statistics->get_option( 'read_capability', 'manage_options' ) );
$manage_cap = wp_statistics_validate_capability( $WP_Statistics->get_option( 'manage_capability', 'manage_options' ) );
/**
* List of WP-Statistics Admin Menu
*
* --- Array Arg -----
* name : Menu name
* title : Page title / if not exist [title == name]
* cap : min require capability @default $read_cap
* icon : Wordpress DashIcon name
* method : method that call in page @default log
* sub : if sub menu , add main menu slug
* page_url : link of Slug Url Page @see WP_Statistics::$page
* break : add new line after sub menu if break key == true
* require : the Condition From Wp-statistics Option if == true for show admin menu
*
*/
$list = array(
'top' => array(
'title' => __( 'Statistics', 'wp-statistics' ),
'page_url' => 'overview',
'method' => 'log',
'icon' => 'dashicons-chart-pie',
),
'overview' => array(
'sub' => 'overview',
'title' => __( 'Overview', 'wp-statistics' ),
'page_url' => 'overview',
),
'hits' => array(
'require' => array( 'visits' ),
'sub' => 'overview',
'title' => __( 'Hits', 'wp-statistics' ),
'page_url' => 'hits',
),
'online' => array(
'require' => array( 'useronline' ),
'sub' => 'overview',
'title' => __( 'Online', 'wp-statistics' ),
'page_url' => 'online',
),
'referrers' => array(
'require' => array( 'visitors' ),
'sub' => 'overview',
'title' => __( 'Referrers', 'wp-statistics' ),
'page_url' => 'referrers',
),
'words' => array(
'require' => array( 'visitors' ),
'sub' => 'overview',
'title' => __( 'Search Words', 'wp-statistics' ),
'page_url' => 'words',
),
'searches' => array(
'require' => array( 'visitors' ),
'sub' => 'overview',
'title' => __( 'Search Engines', 'wp-statistics' ),
'page_url' => 'searches',
),
'pages' => array(
'require' => array( 'pages' ),
'sub' => 'overview',
'title' => __( 'Pages', 'wp-statistics' ),
'page_url' => 'pages',
),
'visitors' => array(
'require' => array( 'visitors' ),
'sub' => 'overview',
'title' => __( 'Visitors', 'wp-statistics' ),
'page_url' => 'visitors',
),
'countries' => array(
'require' => array( 'geoip', 'visitors' ),
'sub' => 'overview',
'title' => __( 'Countries', 'wp-statistics' ),
'page_url' => 'countries',
),
'categories' => array(
'require' => array( 'pages' ),
'sub' => 'overview',
'title' => __( 'Categories', 'wp-statistics' ),
'page_url' => 'categories',
),
'tags' => array(
'require' => array( 'pages' ),
'sub' => 'overview',
'title' => __( 'Tags', 'wp-statistics' ),
'page_url' => 'tags',
),
'authors' => array(
'require' => array( 'pages' ),
'sub' => 'overview',
'title' => __( 'Authors', 'wp-statistics' ),
'page_url' => 'authors',
),
'browsers' => array(
'require' => array( 'visitors' ),
'sub' => 'overview',
'title' => __( 'Browsers', 'wp-statistics' ),
'page_url' => 'browser',
),
'top.visotors' => array(
'require' => array( 'visitors' ),
'sub' => 'overview',
'title' => __( 'Top Visitors Today', 'wp-statistics' ),
'page_url' => 'top-visitors',
),
'exclusions' => array(
'require' => array( 'record_exclusions' ),
'sub' => 'overview',
'title' => __( 'Exclusions', 'wp-statistics' ),
'page_url' => 'exclusions',
'break' => true,
),
'optimize' => array(
'sub' => 'overview',
'title' => __( 'Optimization', 'wp-statistics' ),
'cap' => $manage_cap,
'page_url' => 'optimization',
'method' => 'optimization'
),
'settings' => array(
'sub' => 'overview',
'title' => __( 'Settings', 'wp-statistics' ),
'cap' => $manage_cap,
'page_url' => 'settings',
'method' => 'settings'
),
'plugins' => array(
'sub' => 'overview',
'title' => __( 'Add-Ons', 'wp-statistics' ),
'name' => '<span class="wps-text-warning">' . __( 'Add-Ons', 'wp-statistics' ) . '</span>',
'page_url' => 'plugins',
'method' => 'plugins'
),
'donate' => array(
'sub' => 'overview',
'title' => __( 'Donate', 'wp-statistics' ),
'name' => '<span class="wps-text-success">' . __( 'Donate', 'wp-statistics' ) . '</span>',
'page_url' => 'donate',
'method' => 'donate'
)
);
//Show Admin Menu List
foreach ( $list as $key => $menu ) {
//Check Default variable
$capability = $read_cap;
$method = 'log';
$name = $menu['title'];
if ( array_key_exists( 'cap', $menu ) ) {
$capability = $menu['cap'];
}
if ( array_key_exists( 'method', $menu ) ) {
$method = $menu['method'];
}
if ( array_key_exists( 'name', $menu ) ) {
$name = $menu['name'];
}
//Check if SubMenu or Main Menu
if ( array_key_exists( 'sub', $menu ) ) {
//Check Conditions For Show Menu
if ( wp_statistics_check_option_require( $menu ) === true ) {
$WP_Statistics->menu_slugs[ $key ] = add_submenu_page( WP_Statistics::$page[ $menu['sub'] ], $menu['title'], $name, $capability, WP_Statistics::$page[ $menu['page_url'] ], 'WP_Statistics_Admin_Pages::' . $method );
}
//Check if add Break Line
if ( array_key_exists( 'break', $menu ) ) {
$WP_Statistics->menu_slugs[ 'break_' . $key ] = add_submenu_page( WP_Statistics::$page[ $menu['sub'] ], '', '', $capability, 'wps_break_menu', 'WP_Statistics_Admin_Pages::' . $method );
}
} else {
$WP_Statistics->menu_slugs[ $key ] = add_menu_page( $menu['title'], $name, $capability, WP_Statistics::$page[ $menu['page_url'] ], "WP_Statistics_Admin_Pages::" . $method, $menu['icon'] );
}
}
// Add action to load the meta boxes to the overview page.
add_action( 'load-' . $WP_Statistics->menu_slugs['overview'], 'WP_Statistics_Admin_Pages::overview' );
}
/**
* Enqueue Scripts in Admin Area
*/
public function enqueue_scripts() {
global $pagenow, $WP_Statistics;
// Load our CSS to be used.
wp_enqueue_style( 'wpstatistics-admin-css', WP_Statistics::$reg['plugin-url'] . 'assets/css/admin.css', true, WP_Statistics::$reg['version'] );
if ( is_rtl() ) {
wp_enqueue_style( 'rtl-css', WP_Statistics::$reg['plugin-url'] . 'assets/css/rtl.css', true, WP_Statistics::$reg['version'] );
}
//Load Admin Js
wp_enqueue_script( 'wp-statistics-admin-js', WP_Statistics::$reg['plugin-url'] . 'assets/js/admin.js', array( 'jquery' ), WP_Statistics::$reg['version'] );
//Load Chart Js
$load_in_footer = false;
$load_chart = false;
//Load in Setting Page
$pages_required_chart = array(
'wps_overview_page',
'wps_browsers_page',
'wps_hits_page',
'wps_pages_page',
'wps_categories_page',
'wps_tags_page',
'wps_authors_page',
'wps_searches_page',
);
if ( isset( $_GET['page'] ) and array_search( $_GET['page'], $pages_required_chart ) !== false ) {
$load_chart = true;
}
//Load in Post Page
if ( $pagenow == "post.php" and $WP_Statistics->get_option( 'hit_post_metabox' ) ) {
$load_chart = true;
}
if ( $load_chart === true ) {
wp_enqueue_script( 'wp-statistics-chart-js', WP_Statistics::$reg['plugin-url'] . 'assets/js/Chart.bundle.min.js', false, '2.7.3', $load_in_footer );
}
}
/**
* Admin footer scripts
*/
public function admin_footer_scripts() {
global $WP_Statistics;
// Check to see if the GeoIP database needs to be downloaded and do so if required.
if ( $WP_Statistics->get_option( 'update_geoip' ) ) {
foreach ( WP_Statistics_Updates::$geoip as $geoip_name => $geoip_array ) {
WP_Statistics_Updates::download_geoip( $geoip_name, "update" );
}
}
// Check to see if the referrer spam database needs to be downloaded and do so if required.
if ( $WP_Statistics->get_option( 'update_referrerspam' ) ) {
WP_Statistics_Updates::download_referrerspam();
}
if ( $WP_Statistics->get_option( 'send_upgrade_email' ) ) {
$WP_Statistics->update_option( 'send_upgrade_email', false );
$blogname = get_bloginfo( 'name' );
$blogemail = get_bloginfo( 'admin_email' );
$headers[] = "From: $blogname <$blogemail>";
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/html; charset=utf-8";
if ( $WP_Statistics->get_option( 'email_list' ) == '' ) {
$WP_Statistics->update_option( 'email_list', $blogemail );
}
wp_mail( $WP_Statistics->get_option( 'email_list' ), sprintf( __( 'WP Statistics %s installed on', 'wp-statistics' ), WP_Statistics::$reg['version'] ) . ' ' . $blogname, __( 'Installation/upgrade complete!', 'wp-statistics' ), $headers );
}
}
}

View File

@@ -0,0 +1,435 @@
<?php
/**
* Class WP_Statistics_Ajax
*/
class WP_Statistics_Ajax {
/**
* WP_Statistics_Ajax constructor.
*/
function __construct() {
/**
* List Of Setup Ajax request in Wordpress
*/
$list = array(
'close_notice',
'close_overview_ads',
'delete_agents',
'delete_platforms',
'delete_ip',
'empty_table',
'purge_data',
'purge_visitor_hits',
'get_widget_contents'
);
foreach ( $list as $method ) {
add_action( 'wp_ajax_wp_statistics_' . $method, array( $this, $method . '_action_callback' ) );
}
}
/**
* Setup an AJAX action to close the notice on the overview page.
*/
public function close_notice_action_callback() {
global $WP_Statistics;
$manage_cap = wp_statistics_validate_capability(
$WP_Statistics->get_option( 'manage_capability', 'manage_options' )
);
if ( current_user_can( $manage_cap ) and isset( $_REQUEST['notice'] ) ) {
switch ( $_REQUEST['notice'] ) {
case 'donate':
$WP_Statistics->update_option( 'disable_donation_nag', true );
break;
case 'suggestion':
$WP_Statistics->update_option( 'disable_suggestion_nag', true );
break;
}
$WP_Statistics->update_option( 'admin_notices', false );
}
wp_die();
}
/**
* Close Overview Ads
*/
public function close_overview_ads_action_callback() {
if ( wp_doing_ajax() and isset( $_REQUEST['ads_id'] ) ) {
// Check Security Nonce
check_ajax_referer( 'overview_ads_nonce', 'wps_nonce' );
// Update Option
$get_opt = get_option( 'wp_statistics_overview_page_ads' );
$get_opt['view'] = $_REQUEST['ads_id'];
update_option( 'wp_statistics_overview_page_ads', $get_opt, 'no' );
}
exit;
}
/**
* Setup an AJAX action to delete an agent in the optimization page.
*/
public function delete_agents_action_callback() {
global $WP_Statistics, $wpdb;
$manage_cap = wp_statistics_validate_capability(
$WP_Statistics->get_option( 'manage_capability', 'manage_options' )
);
if ( current_user_can( $manage_cap ) ) {
$agent = $_POST['agent-name'];
if ( $agent ) {
$result = $wpdb->query(
$wpdb->prepare( "DELETE FROM {$wpdb->prefix}statistics_visitor WHERE `agent` = %s", $agent )
);
if ( $result ) {
echo sprintf(
__( '%s agent data deleted successfully.', 'wp-statistics' ),
'<code>' . $agent . '</code>'
);
} else {
_e( 'No agent data found to remove!', 'wp-statistics' );
}
} else {
_e( 'Please select the desired items.', 'wp-statistics' );
}
} else {
_e( 'Access denied!', 'wp-statistics' );
}
wp_die();
}
/**
* Setup an AJAX action to delete a platform in the optimization page.
*/
public function delete_platforms_action_callback() {
global $WP_Statistics, $wpdb;
$manage_cap = wp_statistics_validate_capability(
$WP_Statistics->get_option( 'manage_capability', 'manage_options' )
);
if ( current_user_can( $manage_cap ) ) {
$platform = $_POST['platform-name'];
if ( $platform ) {
$result = $wpdb->query(
$wpdb->prepare( "DELETE FROM {$wpdb->prefix}statistics_visitor WHERE `platform` = %s", $platform )
);
if ( $result ) {
echo sprintf(
__( '%s platform data deleted successfully.', 'wp-statistics' ),
'<code>' . htmlentities( $platform, ENT_QUOTES ) . '</code>'
);
} else {
_e( 'No platform data found to remove!', 'wp-statistics' );
}
} else {
_e( 'Please select the desired items.', 'wp-statistics' );
}
} else {
_e( 'Access denied!', 'wp-statistics' );
}
wp_die();
}
/**
* Setup an AJAX action to delete a ip in the optimization page.
*/
public function delete_ip_action_callback() {
global $WP_Statistics, $wpdb;
$manage_cap = wp_statistics_validate_capability(
$WP_Statistics->get_option( 'manage_capability', 'manage_options' )
);
if ( current_user_can( $manage_cap ) ) {
$ip_address = sanitize_text_field( $_POST['ip-address'] );
if ( $ip_address ) {
$result = $wpdb->query(
$wpdb->prepare( "DELETE FROM {$wpdb->prefix}statistics_visitor WHERE `ip` = %s", $ip_address )
);
if ( $result ) {
echo sprintf(
__( '%s IP data deleted successfully.', 'wp-statistics' ),
'<code>' . htmlentities( $ip_address, ENT_QUOTES ) . '</code>'
);
} else {
_e( 'No IP address data found to remove!', 'wp-statistics' );
}
} else {
_e( 'Please select the desired items.', 'wp-statistics' );
}
} else {
_e( 'Access denied!', 'wp-statistics' );
}
wp_die();
}
/**
* Setup an AJAX action to empty a table in the optimization page.
*/
public function empty_table_action_callback() {
global $WP_Statistics;
//Check isset Table-post
if ( ! isset( $_POST['table-name'] ) ) {
_e( 'Please select the desired items.', 'wp-statistics' );
exit;
}
//Check Valid Table name
$table_name = sanitize_text_field( $_POST['table-name'] );
$list_db_table = wp_statistics_db_table( 'all', 'historical' );
if ( ! array_key_exists( $table_name, $list_db_table ) ) {
_e( 'Access denied!', 'wp-statistics' );
exit;
}
//Check User Cap
$manage_cap = wp_statistics_validate_capability( $WP_Statistics->get_option( 'manage_capability', 'manage_options' ) );
if ( current_user_can( $manage_cap ) ) {
if ( $table_name == "all" ) {
$x_tbl = 1;
foreach ( $list_db_table as $tbl_key => $tbl_name ) {
echo ( $x_tbl > 1 ? '<br>' : '' ) . wp_statitiscs_empty_table( $tbl_name );
$x_tbl ++;
}
} else {
echo wp_statitiscs_empty_table( wp_statistics_db_table( $table_name ) );
}
$WP_Statistics->Primary_Values();
} else {
_e( 'Access denied!', 'wp-statistics' );
}
wp_die();
}
/**
* Setup an AJAX action to purge old data in the optimization page.
*/
public function purge_data_action_callback() {
global $WP_Statistics;
require( WP_Statistics::$reg['plugin-dir'] . 'includes/functions/purge.php' );
$manage_cap = wp_statistics_validate_capability( $WP_Statistics->get_option( 'manage_capability', 'manage_options' ) );
if ( current_user_can( $manage_cap ) ) {
$purge_days = 0;
if ( array_key_exists( 'purge-days', $_POST ) ) {
// Get the number of days to purge data before.
$purge_days = intval( $_POST['purge-days'] );
}
echo wp_statistics_purge_data( $purge_days );
} else {
_e( 'Access denied!', 'wp-statistics' );
}
wp_die();
}
/**
* Setup an AJAX action to purge visitors with more than a defined number of hits.
*/
public function purge_visitor_hits_action_callback() {
global $WP_Statistics;
require( WP_Statistics::$reg['plugin-dir'] . 'includes/functions/purge-hits.php' );
$manage_cap = wp_statistics_validate_capability(
$WP_Statistics->get_option( 'manage_capability', 'manage_options' )
);
if ( current_user_can( $manage_cap ) ) {
$purge_hits = 10;
if ( array_key_exists( 'purge-hits', $_POST ) ) {
// Get the number of days to purge data before.
$purge_hits = intval( $_POST['purge-hits'] );
}
if ( $purge_hits < 10 ) {
_e( 'Number of hits must be greater than or equal to 10!', 'wp-statistics' );
} else {
echo wp_statistics_purge_visitor_hits( $purge_hits );
}
} else {
_e( 'Access denied!', 'wp-statistics' );
}
wp_die();
}
/**
* Setup an AJAX action to purge visitors with more than a defined number of hits.
*/
public function get_widget_contents_action_callback() {
global $WP_Statistics;
$widgets = array(
'about',
'users_online',
'browsers',
'map',
'countries',
'hits',
'hitsmap',
'page',
'pages',
'quickstats',
'recent',
'referring',
'search',
'summary',
'top.visitors',
'words'
);
if ( array_key_exists( 'format', $_POST ) and $_POST['format'] == 'dashboard' ) {
$size = 220;
$days = 10;
} else {
$size = 110;
$days = 20;
}
$view_cap = wp_statistics_validate_capability(
$WP_Statistics->get_option( 'read_capability', 'manage_options' )
);
if ( current_user_can( $view_cap ) ) {
$widget = '';
if ( array_key_exists( 'widget', $_POST ) ) {
// Get the widget we're going to display.
if ( in_array( $_POST['widget'], $widgets ) ) {
$widget = $_POST['widget'];
}
}
if ( $_POST['widget'] == "top_visitors" ) {
$widget = 'top.visitors';
}
if ( 'map' == $widget || 'hitsmap' == $widget ) {
$widget = 'jqv.map';
}
if ( '' == $widget ) {
_e( 'No matching widget found!', 'wp-statistics' );
wp_die();
}
$ISOCountryCode = $WP_Statistics->get_country_codes();
$search_engines = wp_statistics_searchengine_list();
require( WP_Statistics::$reg['plugin-dir'] . 'includes/log/widgets/' . $widget . '.php' );
switch ( $widget ) {
case 'summary':
wp_statistics_generate_summary_postbox_content( $search_engines );
break;
case 'quickstats':
wp_statistics_generate_quickstats_postbox_content( $search_engines );
break;
case 'browsers':
wp_statistics_generate_browsers_postbox_content();
break;
case 'referring':
wp_statistics_generate_referring_postbox_content();
break;
case 'countries':
wp_statistics_generate_countries_postbox_content( $ISOCountryCode );
break;
case 'jqv.map':
wp_statistics_generate_map_postbox_content( $ISOCountryCode );
break;
case 'hits':
wp_statistics_generate_hits_postbox_content( $size, $days );
break;
case 'search':
wp_statistics_generate_search_postbox_content( $search_engines, $size, $days );
break;
case 'words':
wp_statistics_generate_words_postbox_content( $ISOCountryCode );
break;
case 'page':
if ( array_key_exists( 'page-id', $_POST ) ) {
$pageid = (int) $_POST['page-id'];
wp_statistics_generate_page_postbox_content( null, $pageid );
}
break;
case 'pages':
wp_statistics_generate_pages_postbox_content();
break;
case 'recent':
wp_statistics_generate_recent_postbox_content( $ISOCountryCode );
break;
case 'top.visitors':
$format = null;
if ( array_key_exists( 'format', $_POST ) ) {
$format = 'compact';
}
wp_statistics_generate_top_visitors_postbox_content( $ISOCountryCode, 'today', 10, $format );
break;
case 'users_online':
wp_statistics_generate_users_online_postbox_content( $ISOCountryCode );
break;
case 'about':
wp_statistics_generate_about_postbox_content( $ISOCountryCode );
break;
default:
_e( 'ERROR: Widget not found!', 'wp-statistics' );
}
} else {
_e( 'Access denied!', 'wp-statistics' );
}
wp_die();
}
}

View File

@@ -0,0 +1,341 @@
<?php
/**
* Class WP_Statistics_Dashboard
*/
class WP_Statistics_Dashboard {
/**
* User Meta Set Dashboard Option name
* @var string
*/
public static $dashboard_set = 'dashboard_set';
/**
* WP_Statistics_Dashboard constructor.
*/
public function __construct() {
//Register Dashboard Widget
add_action( 'wp_dashboard_setup', array( $this, 'load_dashboard_widget' ) );
//Add Inline Script in Admin Footer
add_action( 'admin_footer', array( $this, 'inline_javascript' ) );
}
/**
* Widget Setup Key
*
* @param $key
* @return string
*/
public static function widget_setup_key( $key ) {
return 'wp-statistics-' . $key . '-widget';
}
/**
* Get Widget List
*
* @param bool $widget
* @return array|mixed
*/
public static function widget_list( $widget = false ) {
/**
* List of WP-Statistics Widget
*
* --- Array Arg -----
* page_url : link of Widget Page @see WP_Statistics::$page
* name : Name Of Widget Box
* require : the Condition From Wp-statistics Option if == true
* hidden : if set true , Default Hidden Dashboard in Wordpress Admin
*
*/
$list = array(
'quickstats' => array(
'page_url' => 'overview',
'name' => __( 'Quick Stats', 'wp-statistics' )
),
'summary' => array(
'name' => __( 'Summary', 'wp-statistics' ),
'hidden' => true
),
'browsers' => array(
'page_url' => 'browser',
'name' => __( 'Top 10 Browsers', 'wp-statistics' ),
'require' => array( 'visitors' ),
'hidden' => true
),
'countries' => array(
'page_url' => 'countries',
'name' => __( 'Top 10 Countries', 'wp-statistics' ),
'require' => array( 'geoip', 'visitors' ),
'hidden' => true
),
'hits' => array(
'page_url' => 'hits',
'name' => __( 'Hit Statistics', 'wp-statistics' ),
'require' => array( 'visits' ),
'hidden' => true
),
'pages' => array(
'page_url' => 'pages',
'name' => __( 'Top 10 Pages', 'wp-statistics' ),
'require' => array( 'pages' ),
'hidden' => true
),
'referring' => array(
'page_url' => 'referrers',
'name' => __( 'Top Referring Sites', 'wp-statistics' ),
'require' => array( 'visitors' ),
'hidden' => true
),
'search' => array(
'page_url' => 'searches',
'name' => __( 'Search Engine Referrals', 'wp-statistics' ),
'require' => array( 'visitors' ),
'hidden' => true
),
'words' => array(
'page_url' => 'words',
'name' => __( 'Latest Search Words', 'wp-statistics' ),
'require' => array( 'visitors' ),
'hidden' => true
),
'top-visitors' => array(
'page_url' => 'top-visitors',
'name' => __( 'Top 10 Visitors Today', 'wp-statistics' ),
'require' => array( 'visitors' ),
'hidden' => true
),
'recent' => array(
'page_url' => 'visitors',
'name' => __( 'Recent Visitors', 'wp-statistics' ),
'require' => array( 'visitors' ),
'hidden' => true
),
'hitsmap' => array(
'name' => __( 'Today\'s Visitors Map', 'wp-statistics' ),
'require' => array( 'visitors' ),
'hidden' => true
)
);
//Print List of Dashboard
if ( $widget === false ) {
return $list;
} else {
if ( array_key_exists( $widget, $list ) ) {
return $list[ $widget ];
}
}
return array();
}
/**
* This function Register Wp-statistics Dashboard to wordpress Admin
*/
public static function register_dashboard_widget() {
//Check Dashboard Widget
if ( ! function_exists( 'wp_add_dashboard_widget' ) ) {
return;
}
//Get List Of Wp-statistics Dashboard Widget
$list = self::widget_list();
foreach ( $list as $widget_key => $dashboard ) {
//Register Dashboard Widget
if ( wp_statistics_check_option_require( $dashboard ) === true ) {
wp_add_dashboard_widget( self::widget_setup_key( $widget_key ), $dashboard['name'], 'WP_Statistics_Dashboard::generate_postbox_contents', $control_callback = null, array( 'widget' => $widget_key ) );
}
}
}
/**
* Load Dashboard Widget
* This Function add_action to `wp_dashboard_setup`
*/
static function load_dashboard_widget() {
global $WP_Statistics;
//Load User Options
$WP_Statistics->load_user_options();
// If the user does not have at least read access to the status plugin, just return without adding the widgets.
if ( ! current_user_can( wp_statistics_validate_capability( $WP_Statistics->get_option( 'read_capability', 'manage_option' ) ) ) ) {
return;
}
//Check Hidden User Dashboard Option
$user_dashboard = $WP_Statistics->get_user_option( self::$dashboard_set );
if ( $user_dashboard === false || $user_dashboard != WP_Statistics::$reg['version'] ) {
self::set_user_hidden_dashboard_option();
}
// If the admin has disabled the widgets, don't display them.
if ( ! $WP_Statistics->get_option( 'disable_dashboard' ) ) {
self::register_dashboard_widget();
}
}
/**
* Set Default Hidden Dashboard User Option
*/
public static function set_user_hidden_dashboard_option() {
global $WP_Statistics;
//Get List Of Wp-statistics Dashboard Widget
$dashboard_list = self::widget_list();
$hidden_opt = 'metaboxhidden_dashboard';
//Create Empty Option and save in User meta
$WP_Statistics->update_user_option( self::$dashboard_set, WP_Statistics::$reg['version'] );
//Get Dashboard Option User Meta
$hidden_widgets = get_user_meta( $WP_Statistics->user_id, $hidden_opt, true );
if ( ! is_array( $hidden_widgets ) ) {
$hidden_widgets = array();
}
//Set Default Hidden Dashboard in Admin Wordpress
foreach ( $dashboard_list as $widget => $dashboard ) {
if ( array_key_exists( 'hidden', $dashboard ) ) {
$hidden_widgets[] = self::widget_setup_key( $widget );
}
}
update_user_meta( $WP_Statistics->user_id, $hidden_opt, $hidden_widgets );
}
/**
* Load Widget Script/style
*/
static function load_widget_css_and_scripts() {
global $WP_Statistics;
// Load the css we use for the statistics pages.
wp_enqueue_style( 'wpstatistics-log-css', WP_Statistics::$reg['plugin-url'] . 'assets/css/log.css', true, '1.2' );
// Load the map code.
if ( ! $WP_Statistics->get_option( 'disable_dashboard' ) ) {
wp_enqueue_style( 'jqvmap-css', WP_Statistics::$reg['plugin-url'] . 'assets/jqvmap/jqvmap.css', true, '1.5.1' );
wp_enqueue_script( 'jquery-vmap', WP_Statistics::$reg['plugin-url'] . 'assets/jqvmap/jquery.vmap.js', true, '1.5.1' );
wp_enqueue_script( 'jquery-vmap-world', WP_Statistics::$reg['plugin-url'] . 'assets/jqvmap/maps/jquery.vmap.world.js', true, '1.5.1' );
}
// Load chart library
if ( ! isset( $_GET['post'] ) ) {
wp_enqueue_script( 'wp-statistics-chart-js', WP_Statistics::$reg['plugin-url'] . 'assets/js/Chart.bundle.min.js', false, '2.7.3', false );
}
//Get current screen page
$screen = get_current_screen();
// Load our custom widgets handling javascript.
if ( 'post' == $screen->id || 'page' == $screen->id ) {
wp_enqueue_script( 'wp_statistics_editor', WP_Statistics::$reg['plugin-url'] . 'assets/js/editor.js' );
} else {
wp_enqueue_script( 'wp_statistics_dashboard', WP_Statistics::$reg['plugin-url'] . 'assets/js/dashboard.js' );
}
}
/**
* Add inline Script
* For Add button Refresh/Direct Button Link in Top of Meta Box
*/
static function inline_javascript() {
//if not Dashboard Page
$screen = get_current_screen();
if ( 'dashboard' != $screen->id ) {
return;
}
//Load Of Require Jquery Library Function
WP_Statistics_Dashboard::load_widget_css_and_scripts();
//Prepare List Of Dashboard
$page_urls = array();
$dashboards = self::widget_list();
foreach ( $dashboards as $widget_key => $dashboard ) {
if ( array_key_exists( 'page_url', $dashboard ) ) {
$page_urls[ 'wp-statistics-' . $widget_key . '-widget_more_button' ] = WP_Statistics_Admin_Pages::admin_url( $dashboard['page_url'] );
}
}
//Add Extra Pages For Overview Page
foreach ( array( 'exclusions' => 'exclusions', 'users_online' => 'online' ) as $p_key => $p_link ) {
$page_urls[ 'wp-statistics-' . $p_key . '-widget_more_button' ] = WP_Statistics_Admin_Pages::admin_url( $p_link );
}
?>
<script type="text/javascript">
var wp_statistics_destinations = <?php echo json_encode( $page_urls ); ?>;
var wp_statistics_loading_image = '<?php echo WP_Statistics_Admin_Pages::loading_meta_box(); ?>';
function wp_statistics_wait_for_postboxes() {
if (!jQuery('#show-settings-link').is(':visible')) {
setTimeout(wp_statistics_wait_for_postboxes, 500);
}
jQuery('.wps-refresh').unbind('click').on('click', wp_statistics_refresh_widget);
jQuery('.wps-more').unbind('click').on('click', wp_statistics_goto_more);
jQuery('.hide-postbox-tog').on('click', wp_statistics_refresh_on_toggle_widget);
}
jQuery(document).ready(function () {
// Add the "more" and "refresh" buttons.
jQuery('.postbox').each(function () {
var temp = jQuery(this);
var temp_id = temp.attr('id');
if (temp_id.substr(0, 14) != 'wp-statistics-') {
return;
}
var temp_html = temp.html();
if (temp_id == '<?php echo self::widget_setup_key( 'summary' ); ?>') {
new_text = '<?php echo WP_Statistics_Admin_Pages::meta_box_button( 'refresh' );?>';
new_text = new_text.replace('{{refreshid}}', temp_id + '_refresh_button');
temp_html = temp_html.replace('</button>', new_text);
} else {
new_text = '<?php echo WP_Statistics_Admin_Pages::meta_box_button();?>';
new_text = new_text.replace('{{refreshid}}', temp_id + '_refresh_button');
new_text = new_text.replace('{{moreid}}', temp_id + '_more_button');
temp_html = temp_html.replace('</button>', new_text);
}
temp.html(temp_html);
});
// We have use a timeout here because we don't now what order this code will run in comparison to the postbox code.
// Any timeout value should work as the timeout won't run until the rest of the javascript as run through once.
setTimeout(wp_statistics_wait_for_postboxes, 100);
});
</script>
<?php
}
/**
* Generate widget Post Box
*
* @param $post
* @param $args
*/
static function generate_postbox_contents( $post, $args ) {
$widget = $args['args']['widget'];
$container_id = 'wp-statistics-' . str_replace( '.', '-', $widget ) . '-div';
echo '<div id="' . $container_id . '">' . WP_Statistics_Admin_Pages::loading_meta_box() . '</div>';
wp_statistics_generate_widget_load_javascript( $widget, $container_id );
}
}

View File

@@ -0,0 +1,201 @@
<?php
/**
* Class WP_Statistics_Editor
*/
class WP_Statistics_Editor {
/**
* Adds a box to the main column on the Post and Page edit screens.
*/
static function add_meta_box() {
global $WP_Statistics;
//Load All User Options
$WP_Statistics->load_user_options();
// We need to fudge the display settings for first time users so not all of the widgets are displayed, we only want to do this on
// the first time they visit the dashboard though so check to see if we've been here before.
if ( ! $WP_Statistics->get_user_option( 'editor_set' ) ) {
$WP_Statistics->update_user_option( 'editor_set', WP_Statistics::$reg['version'] );
$hidden_widgets = get_user_meta( $WP_Statistics->user_id, 'metaboxhidden_post', true );
if ( ! is_array( $hidden_widgets ) ) {
$hidden_widgets = array();
}
if ( ! in_array( 'wp_statistics_editor_meta_box', $hidden_widgets ) ) {
$hidden_widgets[] = 'wp_statistics_editor_meta_box';
}
update_user_meta( $WP_Statistics->user_id, 'metaboxhidden_post', $hidden_widgets );
$hidden_widgets = get_user_meta( $WP_Statistics->user_id, 'metaboxhidden_page', true );
if ( ! is_array( $hidden_widgets ) ) {
$hidden_widgets = array();
}
if ( ! in_array( 'wp_statistics_editor_meta_box', $hidden_widgets ) ) {
$hidden_widgets[] = 'wp_statistics_editor_meta_box';
}
update_user_meta( $WP_Statistics->user_id, 'metaboxhidden_page', $hidden_widgets );
}
// If the user does not have at least read access to the status plugin, just return without adding the widgets.
if ( ! current_user_can( wp_statistics_validate_capability( $WP_Statistics->get_option( 'read_capability', 'manage_option' ) ) ) ) {
return;
}
// If the admin has disabled the widgets don't display them.
if ( $WP_Statistics->get_option( 'disable_editor' ) ) {
return;
}
// If the admin has disabled the Hit Post MetaBox.
if ( ! $WP_Statistics->get_option( 'hit_post_metabox' ) ) {
return;
}
//Show Hit Column in All Post Type in Wordpress
$screens = self::get_list_post_type();
foreach ( $screens as $screen ) {
add_meta_box( 'wp_statistics_editor_meta_box', __( 'Hit Statistics', 'wp-statistics' ), 'WP_Statistics_Editor::meta_box', $screen, 'normal', 'high',
array(
'__block_editor_compatible_meta_box' => true,
'__back_compat_meta_box' => false,
)
);
}
}
static function meta_box( $post ) {
// If the post isn't published yet, don't output the stats as they take too much memory and CPU to compute for no reason.
if ( $post->post_status != 'publish' && $post->post_status != 'private' ) {
_e( 'This post is not yet published.', 'wp-statistics' );
return;
}
add_action( 'admin_footer', 'WP_Statistics_Editor::inline_javascript' );
WP_Statistics_Editor::generate_postbox_contents( $post->ID, array( 'args' => array( 'widget' => 'page' ) ) );
}
static function generate_postbox_contents( $post, $args ) {
if ( self::is_gutenberg() ) {
//If Gutenberg Editor
if ( isset( $_GET['post'] ) and ! empty( $_GET['post'] ) ) {
echo '<div class="wps-gutenberg-chart-js">';
require( WP_Statistics::$reg['plugin-dir'] . 'includes/log/widgets/page.php' );
wp_statistics_generate_page_postbox_content( null, $_GET['post'] );
echo '</div>';
echo '<style>button#wp_statistics_editor_meta_box_more_button { z-index: 9999;position: absolute;top: 1px;right: 3%;}</style>';
}
} else {
$widget = $args['args']['widget'];
$container_id = 'wp-statistics-' . str_replace( '.', '-', $widget ) . '-div';
echo '<div id="' . $container_id . '">' . WP_Statistics_Admin_Pages::loading_meta_box() . '</div>';
echo '<script type="text/javascript">var wp_statistics_current_id = \'' . $post . '\';</script>';
wp_statistics_generate_widget_load_javascript( $widget, $container_id );
}
}
static function inline_javascript() {
$screen = get_current_screen();
$screens = self::get_list_post_type();
if ( ! in_array( $screen->id, $screens ) ) {
return;
}
WP_Statistics_Dashboard::load_widget_css_and_scripts();
$loading_img = WP_Statistics_Admin_Pages::loading_meta_box();
$new_buttons = '</button>';
//If Classic Editor
if ( self::is_gutenberg() === false ) {
$new_buttons .= '<button class="handlediv button-link wps-refresh" type="button" id="{{refreshid}}">' . wp_statistics_icons( 'dashicons-update' ) . '<span class="screen-reader-text">' . __( 'Reload', 'wp-statistics' ) . '</span></button>';
}
$new_buttons .= '<button class="handlediv button-link wps-more" type="button" id="{{moreid}}">' . wp_statistics_icons( 'dashicons-external' ) . '<span class="screen-reader-text">' . __( 'More Details', 'wp-statistics' ) . '</span></button>';
$admin_url = get_admin_url() . "/admin.php?page=";
$page_urls = array();
$page_urls['wp_statistics_editor_meta_box_more_button'] = $admin_url . WP_Statistics::$page['pages'] . '&page-id=';
//Button for Gutenberg
$btn_more_action = 'wp_statistics_goto_more';
if ( self::is_gutenberg() ) {
$btn_more_action = "function () { window.location.href = '" . wp_normalize_path( $page_urls['wp_statistics_editor_meta_box_more_button'] . ( isset( $_GET['post'] ) === true ? $_GET['post'] : '' ) ) . "';}";
}
?>
<script type="text/javascript">
var wp_statistics_destinations = <?php echo json_encode( $page_urls ); ?>;
var wp_statistics_loading_image = '<?php echo $loading_img; ?>';
function wp_statistics_wait_for_postboxes() {
if (!jQuery('#show-settings-link').is(':visible')) {
setTimeout(wp_statistics_wait_for_postboxes, 500);
}
jQuery('.wps-refresh').unbind('click').on('click', wp_statistics_refresh_widget);
jQuery('.wps-more').unbind('click').on('click', <?php echo $btn_more_action; ?>);
jQuery('.hide-postbox-tog').on('click', wp_statistics_refresh_on_toggle_widget);
}
jQuery(document).ready(function () {
// Add the "more" and "refresh" buttons.
jQuery('.postbox').each(function () {
var temp = jQuery(this);
var temp_id = temp.attr('id');
if (temp_id == 'wp_statistics_editor_meta_box') {
var temp_html = temp.html();
new_text = '<?php echo $new_buttons;?>';
new_text = new_text.replace('{{refreshid}}', temp_id + '_refresh_button');
new_text = new_text.replace('{{moreid}}', temp_id + '_more_button');
temp_html = temp_html.replace('</button>', new_text);
temp.html(temp_html);
}
});
// We have use a timeout here because we don't now what order this code will run in comparison to the postbox code.
// Any timeout value should work as the timeout won't run until the rest of the javascript as run through once.
setTimeout(wp_statistics_wait_for_postboxes, 100);
});
</script>
<?php
}
/**
* Get List Post Type
* @return array
*/
public static function get_list_post_type() {
$post_types = array( 'post', 'page' );
$get_post_types = get_post_types( array( 'public' => true, '_builtin' => false ), 'names', 'and' );
foreach ( $get_post_types as $name ) {
$post_types[] = $name;
}
return $post_types;
}
/**
* Check Is Gutenberg Editor
*/
public static function is_gutenberg() {
$current_screen = get_current_screen();
if ( ( method_exists( $current_screen, 'is_block_editor' ) && $current_screen->is_block_editor() ) || ( function_exists( 'is_gutenberg_page' ) ) && is_gutenberg_page() ) {
return true;
}
return false;
}
}

View File

@@ -0,0 +1,343 @@
<?php
/**
* Class WP_Statistics_Export
*/
class WP_Statistics_Export {
/**
* Setup an Export Report Class
*/
public function __construct() {
//Export Data
add_action( 'admin_init', array( $this, 'export_data' ), 9 );
}
/**
* Set the headers to download the export file and then stop running WordPress.
*/
public function export_data() {
if ( isset( $_POST['wps_export'] ) ) {
global $WP_Statistics, $wpdb;
//Set Time Limit Script Run
set_time_limit( 0 );
//Check Wp Nonce and Require Field
if ( ! isset( $_POST['table-to-export'] ) || ! isset( $_POST['export-file-type'] ) || ! isset( $_POST['wps_export_file'] ) || ! wp_verify_nonce( $_POST['wps_export_file'], 'wp_statistics_export_nonce' ) ) {
exit;
}
//Check Current User Capability
$manage_cap = wp_statistics_validate_capability( $WP_Statistics->get_option( 'manage_capability', 'manage_options' ) );
if ( current_user_can( $manage_cap ) ) {
$table = $_POST['table-to-export'];
$type = $_POST['export-file-type'];
// Validate the table name the user passed to us.
$allow_tbl = array( "useronline", "visit", "visitor", "exclusions", "pages", "search" );
if ( ! in_array( $table, $allow_tbl ) ) {
$table = false;
}
// Validate the file type the user passed to us.
if ( ! ( $type == "xml" || $type == "csv" || $type == "tsv" ) ) {
$table = false;
}
if ( $table && $type ) {
$file_name = 'wp-statistics' . '-' . $WP_Statistics->Current_Date( 'Y-m-d-H-i' );
switch ( $type ) {
case 'xml':
$exporter = new ExportDataExcel( 'browser', "{$file_name}.xml" );
break;
case 'csv':
$exporter = new ExportDataCSV( 'browser', "{$file_name}.csv" );
break;
case 'tsv':
$exporter = new ExportDataTSV( 'browser', "{$file_name}.tsv" );
break;
}
$exporter->initialize();
// We need to limit the number of results we retrieve to ensure we don't run out of memory
$query_base = "SELECT * FROM {$wpdb->prefix}statistics_{$table}";
$query = $query_base . ' LIMIT 0,1000';
$i = 1;
$more_results = true;
$result = $wpdb->get_results( $query, ARRAY_A );
// If we didn't get any rows, don't output anything.
if ( count( $result ) < 1 ) {
echo "No data in table!";
exit;
}
if ( isset( $_POST['export-headers'] ) and $_POST['export-headers'] ) {
foreach ( $result[0] as $key => $col ) {
$columns[] = $key;
}
$exporter->addRow( $columns );
}
while ( $more_results ) {
foreach ( $result as $row ) {
$exporter->addRow( $row );
// Make sure we've flushed the output buffer so we don't run out of memory on large exports.
ob_flush();
flush();
}
unset( $result );
$wpdb->flush();
$query = $query_base . ' LIMIT ' . ( $i * 1000 ) . ',1000';
$result = $wpdb->get_results( $query, ARRAY_A );
if ( count( $result ) == 0 ) {
$more_results = false;
}
$i ++;
}
$exporter->finalize();
exit;
}
}
}
}
}
/**
* ExportData is the base class for exporters to specific file formats. See other
* classes below.
*/
abstract class ExportData {
protected $exportTo; // Set in constructor to one of 'browser', 'file', 'string'
protected $stringData; // stringData so far, used if export string mode
protected $tempFile; // handle to temp file (for export file mode)
protected $tempFilename; // temp file name and path (for export file mode)
public $filename; // file mode: the output file name; browser mode: file name for download; string mode: not used
public function __construct( $exportTo = "browser", $filename = "exportdata" ) {
if ( ! in_array( $exportTo, array( 'browser', 'file', 'string' ) ) ) {
throw new Exception( "$exportTo is not a valid ExportData export type" );
}
$this->exportTo = $exportTo;
$this->filename = $filename;
}
public function initialize() {
switch ( $this->exportTo ) {
case 'browser':
$this->sendHttpHeaders();
break;
case 'string':
$this->stringData = '';
break;
case 'file':
$this->tempFilename = tempnam( sys_get_temp_dir(), 'exportdata' );
$this->tempFile = fopen( $this->tempFilename, "w" );
break;
}
$this->write( $this->generateHeader() );
}
public function addRow( $row ) {
$this->write( $this->generateRow( $row ) );
}
public function finalize() {
$this->write( $this->generateFooter() );
switch ( $this->exportTo ) {
case 'browser':
flush();
break;
case 'string':
// do nothing
break;
case 'file':
// close temp file and move it to correct location
fclose( $this->tempFile );
rename( $this->tempFilename, $this->filename );
break;
}
}
public function getString() {
return $this->stringData;
}
abstract public function sendHttpHeaders();
protected function write( $data ) {
switch ( $this->exportTo ) {
case 'browser':
echo $data;
break;
case 'string':
$this->stringData .= $data;
break;
case 'file':
fwrite( $this->tempFile, $data );
break;
}
}
protected function generateHeader() {
// can be overridden by subclass to return any data that goes at the top of the exported file
}
protected function generateFooter() {
// can be overridden by subclass to return any data that goes at the bottom of the exported file
}
// In subclasses generateRow will take $row array and return string of it formatted for export type
abstract protected function generateRow( $row );
}
/**
* ExportDataTSV - Exports to TSV (tab separated value) format.
*/
class ExportDataTSV extends ExportData {
function generateRow( $row ) {
foreach ( $row as $key => $value ) {
// Escape inner quotes and wrap all contents in new quotes.
// Note that we are using \" to escape double quote not ""
$row[ $key ] = '"' . str_replace( '"', '\"', $value ) . '"';
}
return implode( "\t", $row ) . "\n";
}
function sendHttpHeaders() {
header( "Content-type: text/tab-separated-values" );
header( "Content-Disposition: attachment; filename=" . basename( $this->filename ) );
}
}
/**
* ExportDataCSV - Exports to CSV (comma separated value) format.
*/
class ExportDataCSV extends ExportData {
function generateRow( $row ) {
foreach ( $row as $key => $value ) {
// Escape inner quotes and wrap all contents in new quotes.
// Note that we are using \" to escape double quote not ""
$row[ $key ] = '"' . str_replace( '"', '\"', $value ) . '"';
}
return implode( ",", $row ) . "\n";
}
function sendHttpHeaders() {
header( "Content-type: text/csv" );
header( "Content-Disposition: attachment; filename=" . basename( $this->filename ) );
}
}
/**
* Class ExportDataExcel
*/
class ExportDataExcel extends ExportData {
const XmlHeader = "<?xml version=\"1.0\" encoding=\"%s\"?\>\n<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" xmlns:html=\"http://www.w3.org/TR/REC-html40\">";
const XmlFooter = "</Workbook>";
public $encoding = 'UTF-8'; // encoding type to specify in file.
// Note that you're on your own for making sure your data is actually encoded to this encoding
public $title = 'Sheet1'; // title for Worksheet
function generateHeader() {
// workbook header
$output = stripslashes( sprintf( self::XmlHeader, $this->encoding ) ) . "\n";
// Set up styles
$output .= "<Styles>\n";
$output .= "<Style ss:ID=\"sDT\"><NumberFormat ss:Format=\"Short Date\"/></Style>\n";
$output .= "</Styles>\n";
// worksheet header
$output .= sprintf( "<Worksheet ss:Name=\"%s\">\n <Table>\n", htmlentities( $this->title ) );
return $output;
}
function generateFooter() {
$output = '';
// worksheet footer
$output .= " </Table>\n</Worksheet>\n";
// workbook footer
$output .= self::XmlFooter;
return $output;
}
function generateRow( $row ) {
$output = '';
$output .= " <Row>\n";
foreach ( $row as $k => $v ) {
$output .= $this->generateCell( $v );
}
$output .= " </Row>\n";
return $output;
}
private function generateCell( $item ) {
$output = '';
$style = '';
// Tell Excel to treat as a number. Note that Excel only stores roughly 15 digits, so keep
// as text if number is longer than that.
if ( preg_match( "/^-?\d+(?:[.,]\d+)?$/", $item ) && ( strlen( $item ) < 15 ) ) {
$type = 'Number';
}
// Sniff for valid dates; should look something like 2010-07-14 or 7/14/2010 etc. Can
// also have an optional time after the date.
//
// Note we want to be very strict in what we consider a date. There is the possibility
// of really screwing up the data if we try to reformat a string that was not actually
// intended to represent a date.
elseif ( preg_match( "/^(\d{1,2}|\d{4})[\/\-]\d{1,2}[\/\-](\d{1,2}|\d{4})([^\d].+)?$/", $item ) &&
( $timestamp = strtotime( $item ) ) &&
( $timestamp > 0 ) &&
( $timestamp < strtotime( '+500 years' ) ) ) {
$type = 'DateTime';
$item = strftime( "%Y-%m-%dT%H:%M:%S", $timestamp );
$style = 'sDT'; // defined in header; tells excel to format date for display
} else {
$type = 'String';
}
$item = str_replace( '&#039;', '&apos;', htmlspecialchars( $item, ENT_QUOTES ) );
$output .= " ";
$output .= $style ? "<Cell ss:StyleID=\"$style\">" : "<Cell>";
$output .= sprintf( "<Data ss:Type=\"%s\">%s</Data>", $type, $item );
$output .= "</Cell>\n";
return $output;
}
function sendHttpHeaders() {
header( "Content-Type: application/vnd.ms-excel; charset=" . $this->encoding );
header( "Content-Disposition: inline; filename=\"" . basename( $this->filename ) . "\"" );
}
}

View File

@@ -0,0 +1,303 @@
<?php
/**
* Class WP_Statistics_Frontend
*/
class WP_Statistics_Frontend {
public function __construct() {
global $WP_Statistics;
//Enable Shortcode in Widget
add_filter( 'widget_text', 'do_shortcode' );
// Add the honey trap code in the footer.
add_action( 'wp_footer', array( $this, 'add_honeypot' ) );
// Enqueue scripts & styles
add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
//Get Visitor information and Save To Database
add_action( 'wp', array( $this, 'init' ) );
//Add inline Rest Request
add_action( 'wp_head', array( $this, 'add_inline_rest_js' ) );
//Add Html Comment in head
if ( ! $WP_Statistics->use_cache ) {
add_action( 'wp_head', array( $this, 'html_comment' ) );
}
// Check to show hits in posts/pages
if ( $WP_Statistics->get_option( 'show_hits' ) ) {
add_filter( 'the_content', array( $this, 'show_hits' ) );
}
}
/*
* Create Comment support Wappalyzer
*/
public function html_comment() {
echo '<!-- Analytics by WP-Statistics v' . WP_Statistics::$reg['version'] . ' - ' . WP_Statistics::$reg['plugin-data']['PluginURI'] . ' -->' . "\n";
}
/**
* Footer Action
*/
public function add_honeypot() {
global $WP_Statistics;
if ( $WP_Statistics->get_option( 'use_honeypot' ) && $WP_Statistics->get_option( 'honeypot_postid' ) > 0 ) {
$post_url = get_permalink( $WP_Statistics->get_option( 'honeypot_postid' ) );
echo '<a href="' . $post_url . '" style="display: none;">&nbsp;</a>';
}
}
/**
* Enqueue Scripts
*/
public function enqueue_scripts() {
// Load our CSS to be used.
if ( is_admin_bar_showing() ) {
wp_enqueue_style( 'wpstatistics-css', WP_Statistics::$reg['plugin-url'] . 'assets/css/frontend.css', true, WP_Statistics::$reg['version'] );
}
}
/*
* Inline Js
*/
public function add_inline_rest_js() {
global $WP_Statistics;
if ( $WP_Statistics->use_cache ) {
// Wp-Statistics HTML comment
$this->html_comment();
// Prepare Params
$params = array_merge( array(
'_' => time(),
'_wpnonce' => wp_create_nonce( 'wp_rest' ),
WP_Statistics_Rest::_Argument => 'yes',
), self::set_default_params() );
// Return to Page
echo '<script>var WP_Statistics_http = new XMLHttpRequest();WP_Statistics_http.open(\'GET\', \'' . add_query_arg( $params, path_join( get_rest_url(), WP_Statistics_Rest::route . '/' . WP_Statistics_Rest::func ) ) . '\', true);WP_Statistics_http.setRequestHeader("Content-Type", "application/json;charset=UTF-8");WP_Statistics_http.send(null);</script>' . "\n";
}
}
/*
* Set Default Params Rest Api
*/
static public function set_default_params() {
global $WP_Statistics;
/*
* Load Rest Api JavaScript
*/
$params = array();
//Set Browser
$result = $WP_Statistics->get_UserAgent();
$params['browser'] = $result['browser'];
$params['platform'] = $result['platform'];
$params['version'] = $result['version'];
//set referred
$params['referred'] = $WP_Statistics->get_Referred();
//Set ip
$params['ip'] = esc_html( $WP_Statistics->get_IP() );
//exclude
$check_exclude = new WP_Statistics_Hits();
$params['exclude'] = $check_exclude->exclusion_match;
$params['exclude_reason'] = $check_exclude->exclusion_reason;
//User Agent String
$params['ua'] = '';
if ( array_key_exists( 'HTTP_USER_AGENT', $_SERVER ) ) {
$params['ua'] = esc_html( $_SERVER['HTTP_USER_AGENT'] );
}
//track all page
$params['track_all'] = 0;
if ( WP_Statistics_Hits::is_track_page() === true ) {
$params['track_all'] = 1;
}
//timestamp
$params['timestamp'] = $WP_Statistics->current_date( 'U' );
//Wp_query
$get_page_type = WP_Statistics_Frontend::get_page_type();
$params['search_query'] = '';
$params['current_page_type'] = $get_page_type['type'];
$params['current_page_id'] = $get_page_type['id'];
if ( array_key_exists( "search_query", $get_page_type ) ) {
$params['search_query'] = esc_html( $get_page_type['search_query'] );
}
//page url
$params['page_uri'] = wp_statistics_get_uri();
//Get User id
$params['user_id'] = 0;
if ( is_user_logged_in() ) {
$params['user_id'] = get_current_user_id();
}
return $params;
}
/**
* Shutdown Action
*/
public function init() {
global $WP_Statistics;
// If something has gone horribly wrong and $WP_Statistics isn't an object, bail out.
// This seems to happen sometimes with WP Cron calls.
if ( ! is_object( $WP_Statistics ) ) {
return;
}
//Disable if User Active cache Plugin
if ( ! $WP_Statistics->use_cache ) {
$h = new WP_Statistics_GEO_IP_Hits;
// Call the online users tracking code.
if ( $WP_Statistics->get_option( 'useronline' ) ) {
$h->Check_online();
}
// Call the visitor tracking code.
if ( $WP_Statistics->get_option( 'visitors' ) ) {
$h->Visitors();
}
// Call the visit tracking code.
if ( $WP_Statistics->get_option( 'visits' ) ) {
$h->Visits();
}
// Call the page tracking code.
if ( $WP_Statistics->get_option( 'pages' ) ) {
$h->Pages();
}
}
}
/**
* @param $content
*
* @return string
*/
public function show_hits( $content ) {
global $WP_Statistics;
// Get post ID
$post_id = get_the_ID();
// Check post ID
if ( ! $post_id ) {
return $content;
}
// Get post hits
$hits = wp_statistics_pages( 'total', "", $post_id );
$hits_html = '<p>' . sprintf( __( 'Hits: %s', 'wp-statistics' ), $hits ) . '</p>';
// Check hits position
if ( $WP_Statistics->get_option( 'display_hits_position' ) == 'before_content' ) {
return $hits_html . $content;
} elseif ( $WP_Statistics->get_option( 'display_hits_position' ) == 'after_content' ) {
return $content . $hits_html;
} else {
return $content;
}
}
/**
* Get Page Type
*/
public static function get_page_type() {
//Set Default Option
$result = array( "type" => "unknown", "id" => 0 );
//Check Query object
$id = get_queried_object_id();
if ( is_numeric( $id ) and $id > 0 ) {
$result['id'] = $id;
}
//WooCommerce Product
if ( class_exists( 'WooCommerce' ) ) {
if ( is_product() ) {
return wp_parse_args( array( "type" => "product" ), $result );
}
}
//Home Page or Front Page
if ( is_front_page() || is_home() ) {
return wp_parse_args( array( "type" => "home" ), $result );
}
//attachment View
if ( is_attachment() ) {
$result['type'] = "attachment";
}
//is Archive Page
if ( is_archive() ) {
$result['type'] = "archive";
}
//Single Post Fro All Post Type
if ( is_singular() ) {
$result['type'] = "post";
}
//Single Page
if ( is_page() ) {
$result['type'] = "page";
}
//Category Page
if ( is_category() ) {
$result['type'] = "category";
}
//Tag Page
if ( is_tag() ) {
$result['type'] = "post_tag";
}
//is Custom Term From Taxonomy
if ( is_tax() ) {
$result['type'] = "tax";
}
//is Author Page
if ( is_author() ) {
$result['type'] = "author";
}
//is search page
$search_query = filter_var( get_search_query( false ), FILTER_SANITIZE_STRING );
if ( trim( $search_query ) != "" ) {
return array( "type" => "search", "id" => 0, "search_query" => $search_query );
}
//is 404 Page
if ( is_404() ) {
$result['type'] = "404";
}
return $result;
}
}

View File

@@ -0,0 +1,73 @@
<?php
/*
This is the class for recording GeoIP information for hits on the WordPress site. It extends the Hits class.
*/
// Load the classes.
use GeoIp2\Database\Reader;
class WP_Statistics_GEO_IP_Hits extends WP_Statistics_Hits {
public function __construct() {
global $WP_Statistics;
// Call the parent constructor (WP_Statistics::__constructor).
parent::__construct();
// We may have set the location based on a private IP address in the hits class, if so, don't bother looking it up again.
if ( $this->location == '000' ) {
// Now get the location information from the MaxMind database.
try {
// Get the WordPress upload directory information, which is where we have stored the MaxMind database.
$upload_dir = wp_upload_dir();
// Create a new Reader and point it to the database.
$reader = new Reader( $upload_dir['basedir'] . '/wp-statistics/GeoLite2-Country.mmdb' );
// Look up the IP address
$record = $reader->country( $WP_Statistics->ip );
// Get the location.
$location = $record->country->isoCode;
// MaxMind returns a blank for location if it can't find it, but we want to use 000 so replace it.
if ( $location == "" ) {
$location = "000";
}
} catch ( Exception $e ) {
$location = "000";
}
// Store the location in the protected $location variable from the parent class.
$this->location = $location;
}
// Check to see if we are excluded by the GeoIP rules.
if ( ! $this->exclusion_match ) {
// Grab the excluded/included countries lists, force the country codes to be in upper case to match what the GeoIP code uses.
$excluded_countries = explode(
"\n",
strtoupper( str_replace( "\r\n", "\n", $WP_Statistics->get_option( 'excluded_countries' ) ) )
);
$included_countries_string = trim(
strtoupper( str_replace( "\r\n", "\n", $WP_Statistics->get_option( 'included_countries' ) ) )
);
// We need to be really sure this isn't an empty string or explode will return an array with one entry instead of none.
if ( $included_countries_string == '' ) {
$included_countries = array();
} else {
$included_countries = explode( "\n", $included_countries_string );
}
// Check to see if the current location is in the excluded countries list.
if ( in_array( $this->location, $excluded_countries ) ) {
$this->exclusion_match = true;
$this->exclusion_reason = "geoip";
} // Check to see if the current location is not the included countries list.
else if ( ! in_array( $this->location, $included_countries ) && count( $included_countries ) > 0 ) {
$this->exclusion_match = true;
$this->exclusion_reason = "geoip";
}
}
}
}

View File

@@ -0,0 +1,814 @@
<?php
/*
This is the primary class for recording hits on the WordPress site. It extends the WP_Statistics class and is itself extended by the GEO_IP_Hits class.
This class handles; visits, visitors and pages.
*/
use Jaybizzle\CrawlerDetect\CrawlerDetect;
use IPTools\IP;
use IPTools\Network;
use IPTools\Range;
class WP_Statistics_Hits {
// Setup our public/private/protected variables.
public $result = null;
protected $location = '000';
public $exclusion_match = false;
public $exclusion_reason = '';
public $exclusion_record = false;
private $timestamp;
private $current_page_id;
private $current_page_type;
public $current_visitor_id = 0;
// Construction function.
public function __construct() {
global $wp_version, $WP_Statistics;
// Set the timestamp value.
$this->timestamp = $WP_Statistics->current_date( 'U' );
if ( WP_Statistics_Rest::is_rest() ) {
$this->timestamp = WP_Statistics_Rest::params( 'timestamp' );
}
// Check to see if the user wants us to record why we're excluding hits.
if ( $WP_Statistics->get_option( 'record_exclusions' ) ) {
$this->exclusion_record = true;
}
// Create a IP Tools instance from the current IP address for use later.
// Fall back to the localhost if it can't be parsed.
try {
$ip = new IP( $WP_Statistics->ip );
} catch ( Exception $e ) {
$ip = new IP( '127.0.0.1' );
}
// Let's check to see if our subnet matches a private IP address range, if so go ahead and set the location information now.
if ( $WP_Statistics->get_option( 'private_country_code' ) != '000' &&
$WP_Statistics->get_option( 'private_country_code' ) != ''
) {
$private_subnets = array( '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '127.0.0.1/24', 'fc00::/7' );
foreach ( $private_subnets as $psub ) {
try {
$contains_ip = Range::parse( $psub )->contains( $ip );
} catch ( Exception $e ) {
$contains_ip = false;
}
if ( $contains_ip ) {
$this->location = $WP_Statistics->get_option( 'private_country_code' );
break;
}
}
}
/*
* The follow exclusion checks are done during the class construction so we don't have to execute them twice if we're tracking visits and visitors.
*
* Order of exclusion checks is:
* 1 - AJAX calls
* 2 - CronJob
* 3 - Robots
* 4 - IP/Subnets
* 5 - Self Referrals, Referrer Spam & login page
* 6 - User roles
* 7 - Host name list
* 8 - Broken link file
*
* The GoeIP exclusions will be processed in the GeoIP hits class constructor.
*
* Note that we stop processing as soon as a match is made by executing a `return` from the function constructor.
*
*/
if ( WP_Statistics_Rest::is_rest() ) {
$this->exclusion_match = ( WP_Statistics_Rest::params( 'exclude' ) == 1 ? true : false );
$this->exclusion_reason = WP_Statistics_Rest::params( 'exclude_reason' );
if ( $this->exclusion_match === true ) {
return;
}
} else {
// Detect if we're running an ajax request.
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
$this->exclusion_match = true;
$this->exclusion_reason = 'ajax';
return;
}
if ( ( defined( 'DOING_CRON' ) && DOING_CRON === true ) || ( function_exists( 'wp_doing_cron' ) && wp_doing_cron() === true ) ) {
$this->exclusion_match = true;
$this->exclusion_reason = 'cronjob';
return;
}
$crawler = false;
$ua_string = '';
if ( array_key_exists( 'HTTP_USER_AGENT', $_SERVER ) ) {
$ua_string = $_SERVER['HTTP_USER_AGENT'];
}
/*
* Check Is robot
*/
$CrawlerDetect = new CrawlerDetect;
if ( $CrawlerDetect->isCrawler() ) {
$crawler = true;
}
// If we're a crawler as per whichbrowser, exclude us, otherwise double check based on the WP Statistics robot list.
if ( $crawler == true ) {
$this->exclusion_match = true;
$this->exclusion_reason = 'CrawlerDetect';
return;
} else {
// Pull the robots from the database.
$robots = explode( "\n", $WP_Statistics->get_option( 'robotlist' ) );
// Check to see if we match any of the robots.
foreach ( $robots as $robot ) {
$robot = trim( $robot );
// If the match case is less than 4 characters long, it might match too much so don't execute it.
if ( strlen( $robot ) > 3 ) {
if ( stripos( $ua_string, $robot ) !== false ) {
$this->exclusion_match = true;
$this->exclusion_reason = 'robot';
return;
}
}
}
// Finally check to see if we have corrupt header information.
if ( ! $this->exclusion_match && $WP_Statistics->get_option( 'corrupt_browser_info' ) ) {
if ( $ua_string == '' || $WP_Statistics->ip == '' ) {
$this->exclusion_match = true;
$this->exclusion_reason = 'robot';
return;
}
}
}
//Check Broken Link File
if ( is_404() ) {
//Check Current Page
if ( isset( $_SERVER["HTTP_HOST"] ) and isset( $_SERVER["REQUEST_URI"] ) ) {
//Get Full Url Page
$page_url = ( isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] === 'on' ? "https" : "http" ) . "://{$_SERVER["HTTP_HOST"]}{$_SERVER["REQUEST_URI"]}";
//Check Link file
$page_url = parse_url( $page_url, PHP_URL_PATH );
$ext = pathinfo( $page_url, PATHINFO_EXTENSION );
if ( ! empty( $ext ) and $ext != 'php' ) {
$this->exclusion_match = true;
$this->exclusion_reason = 'BrokenFile';
return;
}
}
}
// Pull the subnets from the database.
$subnets = explode( "\n", $WP_Statistics->get_option( 'exclude_ip' ) );
// Check to see if we match any of the excluded addresses.
foreach ( $subnets as $subnet ) {
$subnet = trim( $subnet );
// The shortest ip address is 1.1.1.1, anything less must be a malformed entry.
if ( strlen( $subnet ) > 6 ) {
$range_prased = false;
try {
$range_prased = Range::parse( $subnet )->contains( $ip );
} catch ( Exception $e ) {
$range_parased = false;
}
if ( $range_prased ) {
$this->exclusion_match = true;
$this->exclusion_reason = 'ip match';
return;
}
}
}
// Check to see if we are being referred to ourselves.
if ( $ua_string == 'WordPress/' . $wp_version . '; ' . get_home_url( null, '/' ) ||
$ua_string == 'WordPress/' . $wp_version . '; ' . get_home_url()
) {
$this->exclusion_match = true;
$this->exclusion_reason = 'self referral';
return;
}
// Check to see if we're excluding the login page.
if ( $WP_Statistics->get_option( 'exclude_loginpage' ) ) {
$protocol = strpos( strtolower( $_SERVER['SERVER_PROTOCOL'] ), 'https' ) === false ? 'http' : 'https';
$host = $_SERVER['HTTP_HOST'];
$script = $_SERVER['SCRIPT_NAME'];
$currentURL = $protocol . '://' . $host . $script;
$loginURL = wp_login_url();
if ( $currentURL == $loginURL ) {
$this->exclusion_match = true;
$this->exclusion_reason = 'login page';
return;
}
}
// Check to see if we're excluding the Admin page.
if ( $WP_Statistics->get_option( 'exclude_adminpage' ) ) {
if ( stristr( $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'], "wp-admin" ) ) {
$this->exclusion_match = true;
$this->exclusion_reason = 'admin page';
return;
}
}
// Check to see if we're excluding referrer spam.
if ( $WP_Statistics->get_option( 'referrerspam' ) ) {
$referrer = $WP_Statistics->get_Referred();
// Pull the referrer spam list from the database.
$referrerspamlist = explode( "\n", $WP_Statistics->get_option( 'referrerspamlist' ) );
// Check to see if we match any of the robots.
foreach ( $referrerspamlist as $item ) {
$item = trim( $item );
// If the match case is less than 4 characters long, it might match too much so don't execute it.
if ( strlen( $item ) > 3 ) {
if ( stripos( $referrer, $item ) !== false ) {
$this->exclusion_match = true;
$this->exclusion_reason = 'referrer_spam';
return;
}
}
}
}
// Check to see if we're excluding RSS feeds.
if ( $WP_Statistics->get_option( 'exclude_feeds' ) ) {
if ( is_feed() ) {
$this->exclusion_match = true;
$this->exclusion_reason = 'feed';
return;
}
}
// Check to see if we're excluding 404 pages.
if ( $WP_Statistics->get_option( 'exclude_404s' ) ) {
if ( is_404() ) {
$this->exclusion_match = true;
$this->exclusion_reason = '404';
return;
}
}
// Check to see if we're excluding the current page url.
if ( $WP_Statistics->get_option( 'excluded_urls' ) ) {
$script = $_SERVER['REQUEST_URI'];
$delimiter = strpos( $script, '?' );
if ( $delimiter > 0 ) {
$script = substr( $script, 0, $delimiter );
}
$excluded_urls = explode( "\n", $WP_Statistics->get_option( 'excluded_urls' ) );
foreach ( $excluded_urls as $url ) {
$this_url = trim( $url );
if ( strlen( $this_url ) > 2 ) {
if ( stripos( $script, $this_url ) === 0 ) {
$this->exclusion_match = true;
$this->exclusion_reason = 'excluded url';
return;
}
}
}
}
// Check to see if we are excluding based on the user role.
if ( is_user_logged_in() ) {
$current_user = wp_get_current_user();
foreach ( $current_user->roles as $role ) {
$option_name = 'exclude_' . str_replace( ' ', '_', strtolower( $role ) );
if ( $WP_Statistics->get_option( $option_name ) == true ) {
$this->exclusion_match = true;
$this->exclusion_reason = 'user role';
return;
}
}
}
// Check to see if we are excluded by the host name.
if ( ! $this->exclusion_match ) {
$excluded_host = explode( "\n", $WP_Statistics->get_option( 'excluded_hosts' ) );
// If there's nothing in the excluded host list, don't do anything.
if ( count( $excluded_host ) > 0 ) {
$transient_name = 'wps_excluded_hostname_to_ip_cache';
// Get the transient with the hostname cache.
$hostname_cache = get_transient( $transient_name );
// If the transient has expired (or has never been set), create one now.
if ( $hostname_cache === false ) {
// Flush the failed cache variable.
$hostname_cache = array();
// Loop through the list of hosts and look them up.
foreach ( $excluded_host as $host ) {
if ( strpos( $host, '.' ) > 0 ) {
// We add the extra period to the end of the host name to make sure we don't append the local dns suffix to the resolution cycle.
$hostname_cache[ $host ] = gethostbyname( $host . '.' );
}
}
// Set the transient and store it for 1 hour.
set_transient( $transient_name, $hostname_cache, 360 );
}
// Check if the current IP address matches one of the ones in the excluded hosts list.
if ( in_array( $WP_Statistics->ip, $hostname_cache ) ) {
$this->exclusion_match = true;
$this->exclusion_reason = 'hostname';
return;
}
}
}
}
}
// This function records visits to the site.
public function Visits() {
global $wpdb, $WP_Statistics;
// If we're a webcrawler or referral from ourselves or an excluded address don't record the visit.
if ( ! $this->exclusion_match ) {
// Check to see if we're a returning visitor.
$this->result = $wpdb->get_row( "SELECT * FROM {$wpdb->prefix}statistics_visit ORDER BY `{$wpdb->prefix}statistics_visit`.`ID` DESC" );
// If we're a returning visitor, update the current record in the database, otherwise, create a new one.
if ( $this->result->last_counter != $WP_Statistics->Current_Date( 'Y-m-d' ) ) {
// We'd normally use the WordPress insert function, but since we may run in to a race condition where another hit to the site has already created a new entry in the database
// for this IP address we want to do an "INSERT ... ON DUPLICATE KEY" which WordPress doesn't support.
$sqlstring = $wpdb->prepare(
'INSERT INTO ' . $wpdb->prefix . 'statistics_visit (last_visit, last_counter, visit) VALUES ( %s, %s, %d) ON DUPLICATE KEY UPDATE visit = visit + ' . $WP_Statistics->coefficient,
$WP_Statistics->Current_Date(),
$WP_Statistics->Current_date( 'Y-m-d' ),
$WP_Statistics->coefficient
);
$wpdb->query( $sqlstring );
} else {
$sqlstring = $wpdb->prepare(
'UPDATE ' . $wpdb->prefix . 'statistics_visit SET `visit` = `visit` + %d, `last_visit` = %s WHERE `last_counter` = %s',
$WP_Statistics->coefficient,
$WP_Statistics->Current_Date(),
$this->result->last_counter
);
$wpdb->query( $sqlstring );
}
}
}
//Get current Page detail
public function get_page_detail() {
//if is Cache enable
if ( WP_Statistics_Rest::is_rest() ) {
$this->current_page_id = WP_Statistics_Rest::params( 'current_page_id' );
$this->current_page_type = WP_Statistics_Rest::params( 'current_page_type' );
} else {
//Get Page Type
$get_page_type = WP_Statistics_Frontend::get_page_type();
$this->current_page_id = $get_page_type['id'];
$this->current_page_type = $get_page_type['type'];
}
}
// This function records unique visitors to the site.
public function Visitors() {
global $wpdb, $WP_Statistics;
//Get Current Page detail
$this->get_page_detail();
//Check honeypot Page
if ( $WP_Statistics->get_option( 'use_honeypot' ) && $WP_Statistics->get_option( 'honeypot_postid' ) > 0 && $WP_Statistics->get_option( 'honeypot_postid' ) == $this->current_page_id && $this->current_page_id > 0 ) {
$this->exclusion_match = true;
$this->exclusion_reason = 'honeypot';
}
// If we're a webcrawler or referral from ourselves or an excluded address don't record the visit.
// The exception here is if we've matched a honey page, we want to lookup the user and flag them
// as having been trapped in the honey pot for later exclusions.
if ( $this->exclusion_reason == 'honeypot' || ! $this->exclusion_match ) {
// Check to see if we already have an entry in the database.
$check_ip_db = $WP_Statistics->store_ip_to_db();
if ( $WP_Statistics->ip_hash != false ) {
$check_ip_db = $WP_Statistics->ip_hash;
}
//Check Exist This User in Current Day
$this->result = $wpdb->get_row( "SELECT * FROM `{$wpdb->prefix}statistics_visitor` WHERE `last_counter` = '{$WP_Statistics->Current_Date('Y-m-d')}' AND `ip` = '{$check_ip_db}'" );
// Check to see if this is a visit to the honey pot page, flag it when we create the new entry.
$honeypot = 0;
if ( $this->exclusion_reason == 'honeypot' ) {
$honeypot = 1;
}
// If we don't create a new one, otherwise update the old one.
if ( ! $this->result ) {
// If we've been told to store the entire user agent, do so.
if ( $WP_Statistics->get_option( 'store_ua' ) == true ) {
if ( WP_Statistics_Rest::is_rest() ) {
$ua = WP_Statistics_Rest::params( 'ua' );
} else {
$ua = ( isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '' );
}
} else {
$ua = '';
}
// Store the result.
add_filter( 'query', 'wp_statistics_ignore_insert', 10 );
$wpdb->insert(
$wpdb->prefix . 'statistics_visitor',
array(
'last_counter' => $WP_Statistics->Current_date( 'Y-m-d' ),
'referred' => $WP_Statistics->get_Referred(),
'agent' => $WP_Statistics->agent['browser'],
'platform' => $WP_Statistics->agent['platform'],
'version' => $WP_Statistics->agent['version'],
'ip' => $WP_Statistics->ip_hash ? $WP_Statistics->ip_hash : $WP_Statistics->store_ip_to_db(),
'location' => $this->location,
'UAString' => $ua,
'hits' => 1,
'honeypot' => $honeypot,
),
array( '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s' )
);
$this->current_visitor_id = $wpdb->insert_id;
remove_filter( 'query', 'wp_statistics_ignore_insert', 10 );
// Now parse the referrer and store the results in the search table if the database has been converted.
// Also make sure we actually inserted a row on the INSERT IGNORE above or we'll create duplicate entries.
if ( $wpdb->insert_id ) {
$search_engines = wp_statistics_searchengine_list();
if ( WP_Statistics_Rest::is_rest() ) {
$referred = WP_Statistics_Rest::params( 'referred' );
} else {
$referred = $WP_Statistics->get_Referred();
}
// Parse the URL in to it's component parts.
if ( wp_http_validate_url( $referred ) ) {
$parts = parse_url( $referred );
// Loop through the SE list until we find which search engine matches.
foreach ( $search_engines as $key => $value ) {
$search_regex = wp_statistics_searchengine_regex( $key );
preg_match( '/' . $search_regex . '/', $parts['host'], $matches );
if ( isset( $matches[1] ) ) {
$data['last_counter'] = $WP_Statistics->Current_date( 'Y-m-d' );
$data['engine'] = $key;
$data['words'] = $WP_Statistics->Search_Engine_QueryString( $referred );
$data['host'] = $parts['host'];
$data['visitor'] = $wpdb->insert_id;
if ( $data['words'] == 'No search query found!' ) {
$data['words'] = '';
}
$wpdb->insert( $wpdb->prefix . 'statistics_search', $data );
}
}
}
}
} else {
// Normally we've done all of our exclusion matching during the class creation, however for the robot threshold is calculated here to avoid another call the database.
if ( $WP_Statistics->get_option( 'robot_threshold' ) > 0 && $this->result->hits + 1 > $WP_Statistics->get_option( 'robot_threshold' ) ) {
$this->exclusion_match = true;
$this->exclusion_reason = 'robot_threshold';
} else if ( $this->result->honeypot ) {
$this->exclusion_match = true;
$this->exclusion_reason = 'honeypot';
} else {
//Get Current Visitors ID
$this->current_visitor_id = $this->result->ID;
$sqlstring = $wpdb->prepare(
'UPDATE `' . $wpdb->prefix . 'statistics_visitor` SET `hits` = `hits` + %d, `honeypot` = %d WHERE `ID` = %d',
1,
$honeypot,
$this->result->ID
);
$wpdb->query( $sqlstring );
}
}
}
if ( $this->exclusion_match ) {
$this->RecordExclusion();
}
}
private function RecordExclusion() {
global $wpdb, $WP_Statistics;
// If we're not storing exclusions, just return.
if ( $this->exclusion_record != true ) {
return;
}
$this->result = $wpdb->query( "UPDATE {$wpdb->prefix}statistics_exclusions SET `count` = `count` + 1 WHERE `date` = '{$WP_Statistics->Current_Date( 'Y-m-d' )}' AND `reason` = '{$this->exclusion_reason}'" );
if ( ! $this->result ) {
$wpdb->insert(
$wpdb->prefix . 'statistics_exclusions',
array(
'date' => $WP_Statistics->Current_date( 'Y-m-d' ),
'reason' => $this->exclusion_reason,
'count' => 1,
)
);
}
}
// Check is Track All Page
static public function is_track_page() {
global $WP_Statistics;
//Check if Track All
if ( $WP_Statistics->get_option( 'track_all_pages' ) || is_single() || is_page() || is_front_page() ) {
return true;
}
return false;
}
// This function records page hits.
public function Pages() {
global $wpdb, $WP_Statistics;
// If we're a web crawler or referral from ourselves or an excluded address don't record the page hit.
if ( ! $this->exclusion_match ) {
// Don't track anything but actual pages and posts, unless we've been told to.
$is_track_all = false;
if ( WP_Statistics_Rest::is_rest() ) {
if ( WP_Statistics_Rest::params( 'track_all' ) == 1 ) {
$is_track_all = true;
}
} else {
if ( self::is_track_page() ) {
$is_track_all = true;
}
}
if ( $is_track_all === true ) {
// Get the pages or posts ID if it exists and we haven't set it in the visitors code.
$this->get_page_detail();
// If we didn't find a page id, we don't have anything else to do.
if ( $this->current_page_type == "unknown" ) {
return;
}
// Get the current page URI.
if ( WP_Statistics_Rest::is_rest() ) {
$page_uri = WP_Statistics_Rest::params( 'page_uri' );
} else {
$page_uri = wp_statistics_get_uri();
}
//Get String Search Wordpress
$is_search = false;
if ( WP_Statistics_Rest::is_rest() ) {
if ( WP_Statistics_Rest::params( 'search_query' ) != "" ) {
$page_uri = "?s=" . WP_Statistics_Rest::params( 'search_query' );
$is_search = true;
}
} else {
$get_page_type = WP_Statistics_Frontend::get_page_type();
if ( array_key_exists( "search_query", $get_page_type ) ) {
$page_uri = "?s=" . $get_page_type['search_query'];
$is_search = true;
}
}
if ( $WP_Statistics->get_option( 'strip_uri_parameters' ) and $is_search === false ) {
$temp = explode( '?', $page_uri );
if ( $temp !== false ) {
$page_uri = $temp[0];
}
}
// Limit the URI length to 255 characters, otherwise we may overrun the SQL field size.
$page_uri = substr( $page_uri, 0, 255 );
// If we have already been to this page today (a likely scenario), just update the count on the record.
$exist = $wpdb->get_row( "SELECT `page_id` FROM {$wpdb->prefix}statistics_pages WHERE `date` = '{$WP_Statistics->Current_Date( 'Y-m-d' )}' " . ( $is_search === true ? "AND `uri` = '" . esc_sql( $page_uri ) . "'" : "" ) . "AND `type` = '{$this->current_page_type}' AND `id` = {$this->current_page_id}", ARRAY_A );
if ( null !== $exist ) {
$sql = $wpdb->prepare( "UPDATE {$wpdb->prefix}statistics_pages SET `count` = `count` + 1 WHERE `date` = '{$WP_Statistics->Current_Date( 'Y-m-d' )}' " . ( $is_search === true ? "AND `uri` = '" . esc_sql( $page_uri ) . "'" : "" ) . "AND `type` = '{$this->current_page_type}' AND `id` = %d", $this->current_page_id );
$this->result = $wpdb->query( $sql );
$page_id = $exist['page_id'];
} else {
add_filter( 'query', 'wp_statistics_ignore_insert', 10 );
$wpdb->insert(
$wpdb->prefix . 'statistics_pages',
array(
'uri' => $page_uri,
'date' => $WP_Statistics->Current_date( 'Y-m-d' ),
'count' => 1,
'id' => $this->current_page_id,
'type' => $this->current_page_type
)
);
$page_id = $wpdb->insert_id;
remove_filter( 'query', 'wp_statistics_ignore_insert', 10 );
}
//Set Visitor Relationships
if ( $WP_Statistics->get_option( 'visitors' ) == true and $WP_Statistics->get_option( 'visitors_log' ) == true and $this->current_visitor_id > 0 ) {
$this->visitors_relationships( $page_id, $this->current_visitor_id );
}
}
}
}
//Set Visitor Relationships
public function visitors_relationships( $page_id, $visitor_id ) {
global $wpdb;
$wpdb->insert(
$wpdb->prefix . 'statistics_visitor_relationships',
array(
'visitor_id' => $visitor_id,
'page_id' => $page_id,
'date' => current_time( 'mysql' )
),
array( '%d', '%d', '%s' )
);
}
// This function checks to see if the current user (as defined by their IP address) has an entry in the database.
// Note we set the $this->result variable so we don't have to re-execute the query when we do the user update.
public function Is_user() {
global $wpdb, $WP_Statistics;
// Check to see if we already have an entry in the database.
$check_ip_db = $WP_Statistics->store_ip_to_db();
if ( $WP_Statistics->ip_hash != false ) {
$check_ip_db = $WP_Statistics->ip_hash;
}
//Check Exist
$this->result = $wpdb->query( "SELECT * FROM {$wpdb->prefix}statistics_useronline WHERE `ip` = '{$check_ip_db}'" );
if ( $this->result ) {
return true;
}
}
// This function add/update/delete the online users in the database.
public function Check_online() {
global $WP_Statistics;
// If we're a web crawler or referral from ourselves or an excluded address don't record the user as online, unless we've been told to anyway.
if ( ! $this->exclusion_match || $WP_Statistics->get_option( 'all_online' ) ) {
// If the current user exists in the database already,
// Just update them, otherwise add them
if ( $this->Is_user() ) {
$this->Update_user();
} else {
$this->Add_user();
}
}
}
// This function adds a user to the database.
public function Add_user() {
global $wpdb, $WP_Statistics;
//Check is User
if ( ! $this->Is_user() ) {
// Get the pages or posts ID if it exists and we haven't set it in the visitors code.
$this->get_page_detail();
// Insert the user in to the database.
$wpdb->insert(
$wpdb->prefix . 'statistics_useronline',
array(
'ip' => $WP_Statistics->ip_hash ? $WP_Statistics->ip_hash : $WP_Statistics->store_ip_to_db(),
'timestamp' => $this->timestamp,
'created' => $this->timestamp,
'date' => $WP_Statistics->Current_Date(),
'referred' => $WP_Statistics->get_Referred(),
'agent' => $WP_Statistics->agent['browser'],
'platform' => $WP_Statistics->agent['platform'],
'version' => $WP_Statistics->agent['version'],
'location' => $this->location,
'user_id' => self::get_user_id(),
'page_id' => $this->current_page_id,
'type' => $this->current_page_type
)
);
}
}
/**
* Get User ID
*/
public static function get_user_id() {
//create Empty
$user_id = 0;
//if Rest Request
if ( WP_Statistics_Rest::is_rest() ) {
if ( WP_Statistics_Rest::params( 'user_id' ) != "" ) {
$user_id = WP_Statistics_Rest::params( 'user_id' );
}
} else {
if ( is_user_logged_in() ) {
return get_current_user_id();
}
}
return $user_id;
}
// This function updates a user in the database.
public function Update_user() {
global $wpdb, $WP_Statistics;
// Make sure we found the user earlier when we called Is_user().
if ( $this->result ) {
// Get the pages or posts ID if it exists and we haven't set it in the visitors code.
$this->get_page_detail();
// Update the database with the new information.
$wpdb->update(
$wpdb->prefix . 'statistics_useronline',
array(
'timestamp' => $this->timestamp,
'date' => $WP_Statistics->Current_Date(),
'referred' => $WP_Statistics->get_Referred(),
'user_id' => self::get_user_id(),
'page_id' => $this->current_page_id,
'type' => $this->current_page_type
),
array( 'ip' => $WP_Statistics->ip_hash ? $WP_Statistics->ip_hash : $WP_Statistics->store_ip_to_db() )
);
}
}
}

View File

@@ -0,0 +1,741 @@
<?php
/**
* Class WP_Statistics_Install
*/
class WP_Statistics_Install {
/**
* List Of wp-statistics Mysql Table
* @var array
*/
public static $db_table = array( 'useronline', 'visit', 'visitor', 'exclusions', 'pages', 'search', 'historical', 'visitor_relationships' );
/**
* WP_Statistics_Install constructor.
*
* @internal param $WP_Statistics
*/
function __construct() {
global $WP_Statistics, $wpdb;
if ( is_admin() ) {
// The follow variables are used to define the table structure for new and upgrade installations.
$create_useronline_table = ( "
CREATE TABLE {$wpdb->prefix}statistics_useronline (
ID int(11) NOT NULL AUTO_INCREMENT,
ip varchar(60) NOT NULL,
created int(11),
timestamp int(10) NOT NULL,
date datetime NOT NULL,
referred text CHARACTER SET utf8 NOT NULL,
agent varchar(255) NOT NULL,
platform varchar(255),
version varchar(255),
location varchar(10),
PRIMARY KEY (ID)
) CHARSET=utf8" );
$create_visit_table = ( "
CREATE TABLE {$wpdb->prefix}statistics_visit (
ID int(11) NOT NULL AUTO_INCREMENT,
last_visit datetime NOT NULL,
last_counter date NOT NULL,
visit int(10) NOT NULL,
PRIMARY KEY (ID),
UNIQUE KEY unique_date (last_counter)
) CHARSET=utf8" );
$create_visitor_table = ( "
CREATE TABLE {$wpdb->prefix}statistics_visitor (
ID int(11) NOT NULL AUTO_INCREMENT,
last_counter date NOT NULL,
referred text NOT NULL,
agent varchar(255) NOT NULL,
platform varchar(255),
version varchar(255),
UAString varchar(255),
ip varchar(60) NOT NULL,
location varchar(10),
hits int(11),
honeypot int(11),
PRIMARY KEY (ID),
UNIQUE KEY date_ip_agent (last_counter,ip,agent(75),platform(75),version(75)),
KEY agent (agent),
KEY platform (platform),
KEY version (version),
KEY location (location)
) CHARSET=utf8" );
$create_visitor_table_old = ( "
CREATE TABLE {$wpdb->prefix}statistics_visitor (
ID int(11) NOT NULL AUTO_INCREMENT,
last_counter date NOT NULL,
referred text NOT NULL,
agent varchar(255) NOT NULL,
platform varchar(255),
version varchar(255),
UAString varchar(255),
ip varchar(60) NOT NULL,
location varchar(10),
hits int(11),
honeypot int(11),
PRIMARY KEY (ID),
UNIQUE KEY date_ip_agent (last_counter,ip,agent (75),platform (75),version (75)),
KEY agent (agent),
KEY platform (platform),
KEY version (version),
KEY location (location)
) CHARSET=utf8" );
$create_exclusion_table = ( "
CREATE TABLE {$wpdb->prefix}statistics_exclusions (
ID int(11) NOT NULL AUTO_INCREMENT,
date date NOT NULL,
reason varchar(255) DEFAULT NULL,
count bigint(20) NOT NULL,
PRIMARY KEY (ID),
KEY date (date),
KEY reason (reason)
) CHARSET=utf8" );
$create_pages_table = ( "
CREATE TABLE {$wpdb->prefix}statistics_pages (
uri varchar(255) NOT NULL,
type varchar(255) NOT NULL,
date date NOT NULL,
count int(11) NOT NULL,
id int(11) NOT NULL,
UNIQUE KEY date_2 (date,uri),
KEY url (uri),
KEY date (date),
KEY id (id),
KEY `uri` (`uri`,`count`,`id`)
) CHARSET=utf8" );
$create_historical_table = ( "
CREATE TABLE {$wpdb->prefix}statistics_historical (
ID bigint(20) NOT NULL AUTO_INCREMENT,
category varchar(25) NOT NULL,
page_id bigint(20) NOT NULL,
uri varchar(255) NOT NULL,
value bigint(20) NOT NULL,
PRIMARY KEY (ID),
KEY category (category),
UNIQUE KEY page_id (page_id),
UNIQUE KEY uri (uri)
) CHARSET=utf8" );
$create_search_table = ( "
CREATE TABLE {$wpdb->prefix}statistics_search (
ID bigint(20) NOT NULL AUTO_INCREMENT,
last_counter date NOT NULL,
engine varchar(64) NOT NULL,
host varchar(255),
words varchar(255),
visitor bigint(20),
PRIMARY KEY (ID),
KEY last_counter (last_counter),
KEY engine (engine),
KEY host (host)
) CHARSET=utf8" );
// Check to see if the historical table exists yet, aka if this is a upgrade instead of a first install.
$result = $wpdb->query( "SHOW TABLES WHERE `Tables_in_{$wpdb->dbname}` = '{$wpdb->prefix}statistics_historical'" );
if ( $result == 1 ) {
// Before we update the historical table, check to see if it exists with the old keys
$result = $wpdb->query( "SHOW COLUMNS FROM {$wpdb->prefix}statistics_historical LIKE 'key'" );
if ( $result > 0 ) {
$wpdb->query( "ALTER TABLE `{$wpdb->prefix}statistics_historical` CHANGE `id` `page_id` bigint(20)" );
$wpdb->query( "ALTER TABLE `{$wpdb->prefix}statistics_historical` CHANGE `key` `ID` bigint(20)" );
$wpdb->query( "ALTER TABLE `{$wpdb->prefix}statistics_historical` CHANGE `type` `category` varchar(25)" );
}
}
// This includes the dbDelta function from WordPress.
if ( ! function_exists( 'dbDelta' ) ) {
require( ABSPATH . 'wp-admin/includes/upgrade.php' );
}
// Create/update the plugin tables.
dbDelta( $create_useronline_table );
dbDelta( $create_visit_table );
dbDelta( $create_visitor_table );
dbDelta( $create_exclusion_table );
dbDelta( $create_pages_table );
dbDelta( $create_historical_table );
dbDelta( $create_search_table );
// Some old versions (in the 5.0.x line) of MySQL have issue with the compound index on the visitor table
// so let's make sure it was created, if not, use the older format to create the table manually instead of
// using the dbDelta() call.
$result = $wpdb->query( "SHOW TABLES WHERE `Tables_in_{$wpdb->dbname}` = '{$wpdb->prefix}statistics_visitor'" );
if ( $result != 1 ) {
$wpdb->query( $create_visitor_table_old );
}
// Check to see if the date_ip index still exists, if so get rid of it.
$result = $wpdb->query( "SHOW INDEX FROM {$wpdb->prefix}statistics_visitor WHERE Key_name = 'date_ip'" );
// Note, the result will be the number of fields contained in the index.
if ( $result > 1 ) {
$wpdb->query( "DROP INDEX `date_ip` ON {$wpdb->prefix}statistics_visitor" );
}
// One final database change, drop the 'AString' column from visitors if it exists as it's a typo from an old version.
$result = $wpdb->query( "SHOW COLUMNS FROM {$wpdb->prefix}statistics_visitor LIKE 'AString'" );
if ( $result > 0 ) {
$wpdb->query( "ALTER TABLE `{$wpdb->prefix}statistics_visitor` DROP `AString`" );
}
//Added page_id column in statistics_pages if not exist
$result = $wpdb->query( "SHOW COLUMNS FROM {$wpdb->prefix}statistics_pages LIKE 'page_id'" );
if ( $result == 0 ) {
$wpdb->query( "ALTER TABLE `{$wpdb->prefix}statistics_pages` ADD `page_id` BIGINT(20) NOT NULL AUTO_INCREMENT FIRST, ADD PRIMARY KEY (`page_id`);" );
}
//Added User_id and Page_id in user online table
$result = $wpdb->query( "SHOW COLUMNS FROM {$wpdb->prefix}statistics_useronline LIKE 'user_id'" );
if ( $result == 0 ) {
$wpdb->query( "ALTER TABLE `{$wpdb->prefix}statistics_useronline` ADD `user_id` BIGINT(48) NOT NULL AFTER `location`, ADD `page_id` BIGINT(48) NOT NULL AFTER `user_id`, ADD `type` VARCHAR(100) NOT NULL AFTER `page_id`;" );
$wpdb->query( "DELETE FROM `{$wpdb->prefix}usermeta` WHERE `meta_key` = 'meta-box-order_toplevel_page_wps_overview_page';" );
}
// Store the new version information.
update_option( 'wp_statistics_plugin_version', WP_Statistics::$reg['version'] );
update_option( 'wp_statistics_db_version', WP_Statistics::$reg['version'] );
// Now check to see what database updates may be required and record them for a user notice later.
$dbupdates = array( 'date_ip_agent' => false, 'unique_date' => false );
// Check the number of index's on the visitors table, if it's only 5 we need to check for duplicate entries and remove them
$result = $wpdb->query( "SHOW INDEX FROM {$wpdb->prefix}statistics_visitor WHERE Key_name = 'date_ip_agent'" );
// Note, the result will be the number of fields contained in the index, so in our case 5.
if ( $result != 5 ) {
$dbupdates['date_ip_agent'] = true;
}
// Check the number of index's on the visits table, if it's only 5 we need to check for duplicate entries and remove them
$result = $wpdb->query( "SHOW INDEX FROM {$wpdb->prefix}statistics_visit WHERE Key_name = 'unique_date'" );
// Note, the result will be the number of fields contained in the index, so in our case 1.
if ( $result != 1 ) {
$dbupdates['unique_date'] = true;
}
$WP_Statistics->update_option( 'pending_db_updates', $dbupdates );
$default_options = $WP_Statistics->Default_Options();
if ( WP_Statistics::$installed_version == false ) {
// If this is a first time install, we just need to setup the primary values in the tables.
$WP_Statistics->Primary_Values();
// By default, on new installs, use the new search table.
$WP_Statistics->update_option( 'search_converted', 1 );
} else {
// If this is an upgrade, we need to check to see if we need to convert anything from old to new formats.
// Check to see if the "new" settings code is in place or not, if not, upgrade the old settings to the new system.
if ( get_option( 'wp_statistics' ) === false ) {
$core_options = array(
'wps_disable_map',
'wps_map_location',
'wps_google_coordinates',
'wps_schedule_dbmaint',
'wps_schedule_dbmaint_days',
'wps_geoip',
'wps_update_geoip',
'wps_schedule_geoip',
'wps_last_geoip_dl',
'wps_auto_pop',
'wps_useronline',
'wps_check_online',
'wps_visits',
'wps_visitors',
'wps_visitors_log',
'wps_store_ua',
'wps_coefficient',
'wps_pages',
'wps_track_all_pages',
'wps_use_cache_plugin',
'wps_geoip_city',
'wps_disable_column',
'wps_hit_post_metabox',
'wps_menu_bar',
'wps_hide_notices',
'wps_chart_totals',
'wps_stats_report',
'wps_time_report',
'wps_send_report',
'wps_content_report',
'wps_read_capability',
'wps_manage_capability',
'wps_record_exclusions',
'wps_robotlist',
'wps_exclude_ip',
'wps_exclude_loginpage',
'wps_exclude_adminpage',
);
$var_options = array( 'wps_disable_se_%', 'wps_exclude_%' );
$widget_options = array(
'name_widget',
'useronline_widget',
'tvisit_widget',
'tvisitor_widget',
'yvisit_widget',
'yvisitor_widget',
'wvisit_widget',
'mvisit_widget',
'ysvisit_widget',
'ttvisit_widget',
'ttvisitor_widget',
'tpviews_widget',
'ser_widget',
'select_se',
'tp_widget',
'tpg_widget',
'tc_widget',
'ts_widget',
'tu_widget',
'ap_widget',
'ac_widget',
'au_widget',
'lpd_widget',
'select_lps',
);
// Handle the core options, we're going to strip off the 'wps_' header as we store them in the new settings array.
foreach ( $core_options as $option ) {
$new_name = substr( $option, 4 );
$WP_Statistics->store_option( $new_name, get_option( $option ) );
delete_option( $option );
}
$widget = array();
// Handle the widget options, we're going to store them in a sub-array.
foreach ( $widget_options as $option ) {
$widget[ $option ] = get_option( $option );
delete_option( $option );
}
$WP_Statistics->store_option( 'widget', $widget );
foreach ( $var_options as $option ) {
// Handle the special variables options.
$result = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}options WHERE option_name LIKE '{$option}'" );
foreach ( $result as $opt ) {
$new_name = substr( $opt->option_name, 4 );
$WP_Statistics->store_option( $new_name, $opt->option_value );
delete_option( $opt->option_name );
}
}
$WP_Statistics->save_options();
}
// If the robot list is empty, fill in the defaults.
$wps_temp_robotslist = $WP_Statistics->get_option( 'robotlist' );
if ( trim( $wps_temp_robotslist ) == "" || $WP_Statistics->get_option( 'force_robot_update' ) == true ) {
$WP_Statistics->update_option( 'robotlist', $default_options['robotlist'] );
}
// WP Statistics V4.2 and below automatically exclude the administrator for statistics collection
// newer versions allow the option to be set for any role in WordPress, however we should mimic
// 4.2 behaviour when we upgrade, so see if the option exists in the database and if not, set it.
// This will not work correctly on a WordPress install that has removed the administrator role.
// However that seems VERY unlikely.
$exclude_admins = $WP_Statistics->get_option( 'exclude_administrator', '2' );
if ( $exclude_admins == '2' ) {
$WP_Statistics->update_option( 'exclude_administrator', '1' );
}
// WordPress 4.3 broke the diplay of the sidebar widget because it no longer accepted a null value
// to be returned from the widget update function, let's look to see if we need to update any
// occurances in the options table.
$widget_options = get_option( 'widget_wpstatistics_widget' );
if ( is_array( $widget_options ) ) {
foreach ( $widget_options as $key => $value ) {
// We want to update all null array keys that are integers.
if ( $value === null && is_int( $key ) ) {
$widget_options[ $key ] = array();
}
}
// Store the widget options back to the database.
update_option( 'widget_wpstatistics_widget', $widget_options );
}
}
// We've already handled some of the default or need to do more logic checks on them so create a list to exclude from the next loop.
$excluded_defaults = array( 'force_robot_update', 'robot_list' );
// If this is a first time install or an upgrade and we've added options, set some intelligent defaults.
foreach ( $default_options as $key => $value ) {
if ( ! in_array( $key, $excluded_defaults ) && false === $WP_Statistics->get_option( $key ) ) {
$WP_Statistics->store_option( $key, $value );
}
}
if ( WP_Statistics::$installed_version == false ) {
// We now need to set the robot list to update during the next release. This is only done for new installs to ensure we don't overwrite existing custom robot lists.
$WP_Statistics->store_option( 'force_robot_update', true );
}
// Save the settings now that we've set them.
$WP_Statistics->save_options();
if ( $WP_Statistics->get_option( 'upgrade_report' ) == true ) {
$WP_Statistics->update_option( 'send_upgrade_email', true );
}
// Handle multi site implementations
if ( is_multisite() ) {
$current_blog = get_current_blog_id();
// Loop through each of the sites.
$sites = $WP_Statistics->get_wp_sites_list();
foreach ( $sites as $blog_id ) {
// Since we've just upgraded/installed the current blog, don't execute a remote call for us.
if ( $blog_id != $current_blog ) {
// Get the admin url for the current site.
$url = get_admin_url( $blog_id );
// Go and visit the admin url of the site, this will rerun the install script for each site.
// We turn blocking off because we don't really care about the response so why wait for it.
wp_remote_request( $url, array( 'blocking' => false ) );
}
}
}
}
}
/**
* Setup Visitor RelationShip Table
*/
public static function setup_visitor_relationship_table() {
global $wpdb;
$table_name = $wpdb->prefix . 'statistics_visitor_relationships';
if ( $wpdb->get_var( "SHOW TABLES LIKE '$table_name'" ) != $table_name ) {
// This includes the dbDelta function from WordPress.
if ( ! function_exists( 'dbDelta' ) ) {
require( ABSPATH . 'wp-admin/includes/upgrade.php' );
}
$create_visitor_relationships_table =
"CREATE TABLE IF NOT EXISTS $table_name (
`ID` bigint(20) NOT NULL AUTO_INCREMENT,
`visitor_id` bigint(20) NOT NULL,
`page_id` bigint(20) NOT NULL,
`date` datetime NOT NULL,
PRIMARY KEY (ID),
KEY visitor_id (visitor_id),
KEY page_id (page_id)
) ENGINE=MyISAM DEFAULT CHARSET=utf8";
dbDelta( $create_visitor_relationships_table );
}
}
/**
* Update WordPress Page Type for older wp-statistics Version
*
* @since 12.6
*
* -- List Methods ---
* _init_page_type_updater -> define WordPress Hook
* _get_require_number_update -> Get number of rows that require update page type
* _is_require_update_page -> Check Wp-statistics require update page table
* _get_page_type_by_obj -> Get Page Type by information
*/
public static function _init_page_type_updater() {
# Check Require Admin Process
if ( self::_is_require_update_page() === true ) {
# Add Admin Notice
add_action( 'admin_notices', function () {
echo '<div class="notice notice-info is-dismissible" id="wp-statistics-update-page-area" style="display: none;">';
echo '<p style="margin-top: 17px; float:' . ( is_rtl() ? 'right' : 'left' ) . '">';
echo __( 'WP-Statistics database requires upgrade.', 'wp-statistics' );
echo '</p>';
echo '<div style="float:' . ( is_rtl() ? 'left' : 'right' ) . '">';
echo '<button type="button" id="wps-upgrade-db" class="button button-primary" style="padding: 20px;line-height: 0px;box-shadow: none !important;border: 0px !important;margin: 10px 0;"/>' . __( 'Upgrade Database', 'wp-statistics' ) . '</button>';
echo '</div>';
echo '<div style="clear:both;"></div>';
echo '</div>';
} );
# Add Script
add_action( 'admin_footer', function () {
?>
<script>
jQuery(document).ready(function () {
// Check Page is complete Loaded
jQuery(window).load(function () {
jQuery("#wp-statistics-update-page-area").fadeIn(2000);
jQuery("#wp-statistics-update-page-area button.notice-dismiss").hide();
});
// Update Page type function
function wp_statistics_update_page_type() {
//Complete Progress
let wps_end_progress = `<div id="wps_end_process" style="display:none;">`;
wps_end_progress += `<p>`;
wps_end_progress += `<?php _e( 'Database upgrade operation completed!', 'wp-statistics' ); ?>`;
wps_end_progress += `</p>`;
wps_end_progress += `</div>`;
wps_end_progress += `<button type="button" class="notice-dismiss"><span class="screen-reader-text">Dismiss this notice.</span></button>`;
//new Ajax Request
jQuery.ajax({
url: ajaxurl,
type: 'get',
dataType: "json",
cache: false,
data: {
'action': 'wp_statistics_update_post_type_db',
'number_all': <?php echo self::_get_require_number_update(); ?>
},
success: function (data) {
if (data.process_status === "complete") {
// Get Process Area
let wps_notice_area = jQuery("#wp-statistics-update-page-area");
//Add Html Content
wps_notice_area.html(wps_end_progress);
//Fade in content
jQuery("#wps_end_process").fadeIn(2000);
//enable demiss button
wps_notice_area.removeClass('notice-info').addClass('notice-success');
} else {
//Get number Process
jQuery("span#wps_num_page_process").html(data.number_process);
//Get process Percentage
jQuery("progress#wps_upgrade_html_progress").attr("value", data.percentage);
jQuery("span#wps_num_percentage").html(data.percentage);
//again request
wp_statistics_update_page_type();
}
},
error: function () {
jQuery("#wp-statistics-update-page-area").html('<p><?php _e( 'Error occurred during operation. Please refresh the page.', 'wp-statistics' ); ?></p>');
}
});
}
//Click Start Progress
jQuery(document).on('click', 'button#wps-upgrade-db', function (e) {
e.preventDefault();
// Added Progress Html
let wps_progress = `<div id="wps_process_upgrade" style="display:none;"><p>`;
wps_progress += `<?php _e( 'Please don\'t close the browser window until the database operation was completed.', 'wp-statistic' ); ?>`;
wps_progress += `</p><p><b>`;
wps_progress += `<?php echo __( 'Item processed', 'wp-statistics' ); ?>`;
wps_progress += ` : <span id="wps_num_page_process">0</span> / <?php echo number_format( self::_get_require_number_update() ); ?> &nbsp;<span class="wps-text-warning">(<span id="wps_num_percentage">0</span>%)</span></b></p>`;
wps_progress += '<p><progress id="wps_upgrade_html_progress" value="0" max="100" style="height: 20px;width: 100%;"></progress></p></div>';
// set new Content
jQuery("#wp-statistics-update-page-area").html(wps_progress);
jQuery("#wps_process_upgrade").fadeIn(2000);
// Run WordPress Ajax Updator
wp_statistics_update_page_type();
});
//Remove Notice event
jQuery(document).on('click', '#wp-statistics-update-page-area button.notice-dismiss', function (e) {
e.preventDefault();
jQuery("#wp-statistics-update-page-area").fadeOut('normal');
});
});
</script>
<?php
} );
}
# Add Admin Ajax Process
add_action( 'wp_ajax_wp_statistics_update_post_type_db', function () {
global $wpdb;
# Create Default Obj
$return = array( 'process_status' => 'complete', 'number_process' => 0, 'percentage' => 0 );
# Check is Ajax WordPress
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
# Check Status Of Process
if ( self::_is_require_update_page() === true ) {
# Number Process Per Query
$number_per_query = 80;
# Check Number Process
$number_process = self::_get_require_number_update();
$i = 0;
if ( $number_process > 0 ) {
# Start Query
$query = $wpdb->get_results( "SELECT * FROM `" . wp_statistics_db_table( 'pages' ) . "` WHERE `type` = '' ORDER BY `page_id` DESC LIMIT 0,{$number_per_query}", ARRAY_A );
foreach ( $query as $row ) {
# Get Page Type
$page_type = self::_get_page_type_by_obj( $row['id'], $row['uri'] );
# Update Table
$wpdb->update(
wp_statistics_db_table( 'pages' ),
array(
'type' => $page_type
),
array( 'page_id' => $row['page_id'] )
);
$i ++;
}
if ( $_GET['number_all'] > $number_per_query ) {
# calculate number process
$return['number_process'] = $_GET['number_all'] - ( $number_process - $i );
# Calculate Per
$return['percentage'] = round( ( $return['number_process'] / $_GET['number_all'] ) * 100 );
# Set Process
$return['process_status'] = 'incomplete';
} else {
$return['number_process'] = $_GET['number_all'];
$return['percentage'] = 100;
update_option( 'wp_statistics_update_page_type', 'yes' );
}
}
} else {
# Closed Process
update_option( 'wp_statistics_update_page_type', 'yes' );
}
# Export Data
wp_send_json( $return );
exit;
}
} );
}
public static function _get_require_number_update() {
global $wpdb;
return $wpdb->get_var( "SELECT COUNT(*) FROM `" . wp_statistics_db_table( 'pages' ) . "` WHERE `type` = ''" );
}
public static function _is_require_update_page() {
# require update option name
$opt_name = 'wp_statistics_update_page_type';
# Check exist option
$get_opt = get_option( $opt_name );
if ( ! empty( $get_opt ) ) {
return false;
}
# Check number require row
if ( self::_get_require_number_update() > 0 ) {
return true;
}
return false;
}
public static function _get_page_type_by_obj( $obj_ID, $page_url ) {
//Default page type
$page_type = 'unknown';
//check if Home Page
if ( $page_url == "/" ) {
return 'home';
} else {
// Page url
$page_url = ltrim( $page_url, "/" );
$page_url = trim( get_bloginfo( 'url' ), "/" ) . "/" . $page_url;
// Check Page Path is exist
$exist_page = url_to_postid( $page_url );
//Check Post Exist
if ( $exist_page > 0 ) {
# Get Post Type
$p_type = get_post_type( $exist_page );
# Check Post Type
if ( $p_type == "product" ) {
$page_type = 'product';
} elseif ( $p_type == "page" ) {
$page_type = 'page';
} elseif ( $p_type == "attachment" ) {
$page_type = 'attachment';
} else {
$page_type = 'post';
}
} else {
# Check is Term
$term = get_term( $obj_ID );
if ( is_wp_error( get_term_link( $term ) ) === true ) {
//Don't Stuff
} else {
//Which Taxonomy
$taxonomy = $term->taxonomy;
//Check Url is contain
$term_link = get_term_link( $term );
$term_link = ltrim( str_ireplace( get_bloginfo( 'url' ), "", $term_link ), "/" );
if ( stristr( $page_url, $term_link ) === false ) {
//Return Unknown
} else {
//Check Type of taxonomy
if ( $taxonomy == "category" ) {
$page_type = 'category';
} elseif ( $taxonomy == "post_tag" ) {
$page_type = 'post_tag';
} else {
$page_type = 'tax';
}
}
}
}
}
return $page_type;
}
}

View File

@@ -0,0 +1,127 @@
<?php
/**
* Class WP_Statistics_Network_Admin
*/
class WP_Statistics_Network_Admin {
/**
* This function adds the primary menu to WordPress network.
*/
static function menu() {
global $WP_Statistics;
// Get the read/write capabilities required to view/manage the plugin as set by the user.
$read_cap = wp_statistics_validate_capability( $WP_Statistics->get_option( 'read_capability', 'manage_options' ) );
$manage_cap = wp_statistics_validate_capability( $WP_Statistics->get_option( 'manage_capability', 'manage_options' ) );
// Add the top level menu.
add_menu_page( __( 'Statistics', 'wp-statistics' ), __( 'Statistics', 'wp-statistics' ), $read_cap, WP_Statistics::$reg['main-file'], 'WP_Statistics_Network_Admin::overview', 'dashicons-chart-pie' );
// Add the sub items.
add_submenu_page( WP_Statistics::$reg['main-file'], __( 'Overview', 'wp-statistics' ), __( 'Overview', 'wp-statistics' ), $read_cap, WP_Statistics::$reg['main-file'], 'WP_Statistics_Network_Admin::overview' );
$count = 0;
$sites = $WP_Statistics->get_wp_sites_list();
foreach ( $sites as $blog_id ) {
$details = get_blog_details( $blog_id );
add_submenu_page( WP_Statistics::$reg['main-file'], $details->blogname, $details->blogname, $manage_cap, 'wp_statistics_blogid_' . $blog_id, 'WP_Statistics_Network_Admin::goto_blog' );
$count ++;
if ( $count > 15 ) {
break;
}
}
}
/**
* Network Overview
*/
static function overview() {
global $WP_Statistics;
?>
<div id="wrap wps-wrap">
<br/>
<table class="widefat wp-list-table" style="width: auto;">
<thead>
<tr>
<th style='text-align: left'><?php _e( 'Site', 'wp-statistics' ); ?></th>
<th style='text-align: left'><?php _e( 'Options', 'wp-statistics' ); ?></th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
$options = array(
__( 'Overview', 'wp-statistics' ) => WP_Statistics::$page['overview'],
__( 'Hits', 'wp-statistics' ) => WP_Statistics::$page['hits'],
__( 'Online', 'wp-statistics' ) => WP_Statistics::$page['online'],
__( 'Referrers', 'wp-statistics' ) => WP_Statistics::$page['referrers'],
__( 'Search Words', 'wp-statistics' ) => WP_Statistics::$page['words'],
__( 'Searches', 'wp-statistics' ) => WP_Statistics::$page['searches'],
__( 'Pages', 'wp-statistics' ) => WP_Statistics::$page['pages'],
__( 'Visitors', 'wp-statistics' ) => WP_Statistics::$page['visitors'],
__( 'Countries', 'wp-statistics' ) => WP_Statistics::$page['countries'],
__( 'Browsers', 'wp-statistics' ) => WP_Statistics::$page['browser'],
__( 'Top Visitors Today', 'wp-statistics' ) => WP_Statistics::$page['top-visitors'],
__( 'Exclusions', 'wp-statistics' ) => WP_Statistics::$page['exclusions'],
__( 'Optimization', 'wp-statistics' ) => WP_Statistics::$page['optimization'],
__( 'Settings', 'wp-statistics' ) => WP_Statistics::$page['settings'],
);
$sites = $WP_Statistics->get_wp_sites_list();
foreach ( $sites as $blog_id ) {
$details = get_blog_details( $blog_id );
$url = get_admin_url( $blog_id, '/' ) . 'admin.php?page=';
$alternate = '';
if ( $i % 2 == 0 ) {
$alternate = ' class="alternate"';
}
?>
<tr<?php echo $alternate; ?>>
<td style='text-align: left'>
<?php echo $details->blogname; ?>
</td>
<td style='text-align: left'>
<?php
$options_len = count( $options );
$j = 0;
foreach ( $options as $key => $value ) {
echo '<a href="' . $url . $value . '">' . $key . '</a>';
$j ++;
if ( $j < $options_len ) {
echo ' - ';
}
}
?>
</td>
</tr>
<?php
$i ++;
}
?>
</tbody>
</table>
</div>
<?php
}
/**
* Goto Network Blog
*/
static function goto_blog() {
global $plugin_page;
$blog_id = str_replace( 'wp_statistics_blogid_', '', $plugin_page );
// Get the admin url for the current site.
$url = get_admin_url( $blog_id ) . '/admin.php?page=' . WP_Statistics::$page['overview'];
echo "<script>window.location.href = '$url';</script>";
}
}

View File

@@ -0,0 +1,156 @@
<?php
/**
* Class WP_Statistics_Rest
*/
class WP_Statistics_Rest {
// Set Default namespace
const route = 'wpstatistics/v1';
// Set Default Statistic Save method
const func = 'hit';
// Set Default Name
const _Argument = 'wp_statistics_hit_rest';
/**
* Setup an Wordpress REst Api action.
*/
public function __construct() {
global $WP_Statistics;
/*
* add Router Rest Api
*/
if ( isset( $WP_Statistics ) and $WP_Statistics->use_cache ) {
add_action( 'rest_api_init', array( $this, 'register_routes' ) );
}
}
/**
* List Of Required Params
*
* @return array
*/
public static function require_params_hit() {
return array(
'browser',
'platform',
'version',
'ip',
'track_all',
'timestamp',
'page_uri',
'user_id',
);
}
/*
* Add Endpoint Route
*/
public function register_routes() {
// Create Require Params
$params = array();
foreach ( self::require_params_hit() as $p ) {
$params[ $p ] = array( 'required' => true );
}
// Get Hit
register_rest_route( self::route, '/' . self::func, array(
'methods' => \WP_REST_Server::READABLE,
'permission_callback' => function () {
global $WP_Statistics;
return ( $WP_Statistics->get_option( 'use_cache_plugin' ) == 1 ? true : false );
},
'callback' => array( $this, 'hit' ),
'args' => array_merge(
array( '_wpnonce' => array(
'required' => true,
'validate_callback' => function ( $value ) {
return wp_verify_nonce( $value, 'wp_rest' );
}
) ), $params )
) );
}
/*
* Wp Statistic Hit Save
*/
public function hit() {
global $WP_Statistics;
/*
* Check Is Test Service Request
*/
if ( isset( $_REQUEST['rest-api-wp-statistics'] ) ) {
return array( "rest-api-wp-statistics" => "OK" );
}
// Check Isset global
if ( ! is_object( $WP_Statistics ) ) {
return;
}
$h = new WP_Statistics_GEO_IP_Hits;
// Call the online users tracking code.
if ( $WP_Statistics->get_option( 'useronline' ) ) {
$h->Check_online();
}
// Call the visitor tracking code.
if ( $WP_Statistics->get_option( 'visitors' ) ) {
$h->Visitors();
}
// Call the visit tracking code.
if ( $WP_Statistics->get_option( 'visits' ) ) {
$h->Visits();
}
// Call the page tracking code.
if ( $WP_Statistics->get_option( 'pages' ) ) {
$h->Pages();
}
// Set Return
return new \WP_REST_Response( array( 'status' => true, 'message' => __( 'Visitor Hit was recorded successfully.', 'wp-statistics' ) ) );
}
/*
* Check is Rest Request
*/
static public function is_rest() {
global $WP_Statistics;
if ( isset( $WP_Statistics ) and defined( 'REST_REQUEST' ) && REST_REQUEST and $WP_Statistics->use_cache ) {
if ( isset( $_REQUEST[ self::_Argument ] ) ) {
return true;
}
}
return false;
}
/*
* Get Params Request
*/
static public function params( $params ) {
if ( defined( 'REST_REQUEST' ) && REST_REQUEST and isset( $_REQUEST[ self::_Argument ] ) ) {
$data = array();
foreach ( $_REQUEST as $key => $value ) {
if ( ! in_array( $key, array( '_', '_wpnonce' ) ) ) {
$data[ $key ] = trim( $value );
}
}
if ( isset( $data[ $params ] ) ) {
return $data[ $params ];
}
}
return false;
}
}

View File

@@ -0,0 +1,251 @@
<?php
/**
* Class WP_Statistics_Schedule
*/
class WP_Statistics_Schedule {
/**
* WP_Statistics_Schedule constructor.
*
* @param $WP_Statistics
*/
function __construct() {
global $WP_Statistics;
// before construct
add_filter( 'cron_schedules', 'WP_Statistics_Schedule::addcron' );
//Run This Method Only Admin Area
if ( is_admin() ) {
//Disable Run to Ajax
if ( ! wp_doing_ajax() ) {
// Add the GeoIP update schedule if it doesn't exist and it should be.
if ( ! wp_next_scheduled( 'wp_statistics_geoip_hook' ) && $WP_Statistics->get_option( 'schedule_geoip' ) && $WP_Statistics->get_option( 'geoip' ) ) {
wp_schedule_event( time(), 'daily', 'wp_statistics_geoip_hook' );
}
// Remove the GeoIP update schedule if it does exist and it should shouldn't.
if ( wp_next_scheduled( 'wp_statistics_geoip_hook' ) && ( ! $WP_Statistics->get_option( 'schedule_geoip' ) || ! $WP_Statistics->get_option( 'geoip' ) ) ) {
wp_unschedule_event( wp_next_scheduled( 'wp_statistics_geoip_hook' ), 'wp_statistics_geoip_hook' );
}
//Construct Event
add_action( 'wp_statistics_geoip_hook', array( $this, 'geoip_event' ) );
}
} else {
// Add the report schedule if it doesn't exist and is enabled.
if ( ! wp_next_scheduled( 'report_hook' ) && $WP_Statistics->get_option( 'stats_report' ) ) {
wp_schedule_event( time(), $WP_Statistics->get_option( 'time_report' ), 'report_hook' );
}
// Remove the report schedule if it does exist and is disabled.
if ( wp_next_scheduled( 'report_hook' ) && ! $WP_Statistics->get_option( 'stats_report' ) ) {
wp_unschedule_event( wp_next_scheduled( 'report_hook' ), 'report_hook' );
}
// Add the referrerspam update schedule if it doesn't exist and it should be.
if ( ! wp_next_scheduled( 'wp_statistics_referrerspam_hook' ) && $WP_Statistics->get_option( 'schedule_referrerspam' ) ) {
wp_schedule_event( time(), 'weekly', 'wp_statistics_referrerspam_hook' );
}
// Remove the referrerspam update schedule if it does exist and it should shouldn't.
if ( wp_next_scheduled( 'wp_statistics_referrerspam_hook' ) && ! $WP_Statistics->get_option( 'schedule_referrerspam' ) ) {
wp_unschedule_event( wp_next_scheduled( 'wp_statistics_referrerspam_hook' ), 'wp_statistics_referrerspam_hook' );
}
// Add the database maintenance schedule if it doesn't exist and it should be.
if ( ! wp_next_scheduled( 'wp_statistics_dbmaint_hook' ) && $WP_Statistics->get_option( 'schedule_dbmaint' ) ) {
wp_schedule_event( time(), 'daily', 'wp_statistics_dbmaint_hook' );
}
// Remove the database maintenance schedule if it does exist and it shouldn't.
if ( wp_next_scheduled( 'wp_statistics_dbmaint_hook' ) && ( ! $WP_Statistics->get_option( 'schedule_dbmaint' ) ) ) {
wp_unschedule_event( wp_next_scheduled( 'wp_statistics_dbmaint_hook' ), 'wp_statistics_dbmaint_hook' );
}
// Add the visitor database maintenance schedule if it doesn't exist and it should be.
if ( ! wp_next_scheduled( 'wp_statistics_dbmaint_visitor_hook' ) && $WP_Statistics->get_option( 'schedule_dbmaint_visitor' ) ) {
wp_schedule_event( time(), 'daily', 'wp_statistics_dbmaint_visitor_hook' );
}
// Remove the visitor database maintenance schedule if it does exist and it shouldn't.
if ( wp_next_scheduled( 'wp_statistics_dbmaint_visitor_hook' ) && ( ! $WP_Statistics->get_option( 'schedule_dbmaint_visitor' ) ) ) {
wp_unschedule_event( wp_next_scheduled( 'wp_statistics_dbmaint_visitor_hook' ), 'wp_statistics_dbmaint_visitor_hook' );
}
// Remove the add visit row schedule if it does exist and it shouldn't.
if ( wp_next_scheduled( 'wp_statistics_add_visit_hook' ) && ( ! $WP_Statistics->get_option( 'visits' ) ) ) {
wp_unschedule_event( wp_next_scheduled( 'wp_statistics_add_visit_hook' ), 'wp_statistics_add_visit_hook' );
}
// Add the add visit table row schedule if it does exist and it should.
if ( ! wp_next_scheduled( 'wp_statistics_add_visit_hook' ) && $WP_Statistics->get_option( 'visits' ) ) {
wp_schedule_event( time(), 'daily', 'wp_statistics_add_visit_hook' );
}
//after construct
add_action( 'wp_statistics_add_visit_hook', array( $this, 'add_visit_event' ) );
add_action( 'wp_statistics_dbmaint_hook', array( $this, 'dbmaint_event' ) );
add_action( 'wp_statistics_dbmaint_visitor_hook', array( $this, 'dbmaint_visitor_event' ) );
add_action( 'report_hook', array( $this, 'send_report' ) );
}
}
/**
* @param array $schedules
* @return mixed
*/
static function addcron( $schedules ) {
// Adds once weekly to the existing schedules.
if ( ! array_key_exists( 'weekly', $schedules ) ) {
$schedules['weekly'] = array(
'interval' => 604800,
'display' => __( 'Once Weekly' ),
);
}
if ( ! array_key_exists( 'biweekly', $schedules ) ) {
$schedules['biweekly'] = array(
'interval' => 1209600,
'display' => __( 'Once Every 2 Weeks' ),
);
}
if ( ! array_key_exists( '4weeks', $schedules ) ) {
$schedules['4weeks'] = array(
'interval' => 2419200,
'display' => __( 'Once Every 4 Weeks' ),
);
}
return $schedules;
}
/**
* adds a record for tomorrow to the visit table to avoid a race condition.
*
*/
public function add_visit_event() {
global $wpdb, $WP_Statistics;
$wpdb->insert(
$wpdb->prefix . 'statistics_visit',
array(
'last_visit' => $WP_Statistics->Current_Date( null, '+1' ),
'last_counter' => $WP_Statistics->Current_date( 'Y-m-d', '+1' ),
'visit' => 0,
),
array( '%s', '%s', '%d' )
);
}
/**
* Updates the GeoIP database from MaxMind.
*/
public function geoip_event() {
global $WP_Statistics;
// Maxmind updates the geoip database on the first Tuesday of the month, to make sure we don't update before they post
// the update, download it two days later.
$thisupdate = strtotime( __( 'First Tuesday of this month', 'wp-statistics' ) ) + ( 86400 * 2 );
$lastupdate = $WP_Statistics->get_option( 'last_geoip_dl' );
$upload_dir = wp_upload_dir();
// We're also going to look to see if our filesize is to small, this means the plugin stub still exists and should
// be replaced with a proper file.
$is_require_update = false;
foreach ( WP_Statistics_Updates::$geoip as $geoip_name => $geoip_array ) {
$file_path = $upload_dir['basedir'] . '/wp-statistics/' . WP_Statistics_Updates::$geoip[ $geoip_name ]['file'] . '.mmdb';
if ( file_exists( $file_path ) ) {
if ( $lastupdate < $thisupdate ) {
$is_require_update = true;
}
}
}
if ( $is_require_update === true ) {
// We can't fire the download function directly here as we rely on some functions that haven't been loaded yet
// in WordPress, so instead just set the flag in the options table and the shutdown hook will take care of the
// actual download at the end of the page.
$WP_Statistics->update_option( 'update_geoip', true );
}
}
/**
* Purges old records on a schedule based on age.
*/
public function dbmaint_event() {
global $WP_Statistics;
if ( ! function_exists( 'wp_statistics_purge_data' ) ) {
require( WP_Statistics::$reg['plugin-dir'] . 'includes/functions/purge.php' );
}
$purge_days = intval( $WP_Statistics->get_option( 'schedule_dbmaint_days', false ) );
wp_statistics_purge_data( $purge_days );
}
/**
* Purges visitors with more than a defined number of hits in a day.
*/
public function dbmaint_visitor_event() {
global $WP_Statistics;
if ( ! function_exists( 'wp_statistics_purge_visitor_hits' ) ) {
require( WP_Statistics::$reg['plugin-dir'] . 'includes/functions/purge-hits.php' );
}
$purge_hits = intval( $WP_Statistics->get_option( 'schedule_dbmaint_visitor_hits', false ) );
wp_statistics_purge_visitor_hits( $purge_hits );
}
/**
* Sends the statistics report to the selected users.
*/
public function send_report() {
global $WP_Statistics, $sms;
// Retrieve the template from the options.
$final_text_report = $WP_Statistics->get_option( 'content_report' );
// Process shortcodes in the template. Note that V8.0 upgrade script replaced the old %option% codes with the appropriate short codes.
$final_text_report = do_shortcode( $final_text_report );
$final_text_report = apply_filters( 'wp_statistics_final_text_report_email', $final_text_report );
// Send the report through the selected transport agent.
if ( $WP_Statistics->get_option( 'send_report' ) == 'mail' ) {
$blogname = get_bloginfo( 'name' );
$blogemail = get_bloginfo( 'admin_email' );
$headers[] = "From: $blogname <$blogemail>";
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/html; charset=utf-8";
if ( $WP_Statistics->get_option( 'email_list' ) == '' ) {
$WP_Statistics->update_option( 'email_list', $blogemail );
}
wp_mail( $WP_Statistics->get_option( 'email_list' ), __( 'Statistical reporting', 'wp-statistics' ), $final_text_report, $headers );
} else if ( $WP_Statistics->get_option( 'send_report' ) == 'sms' ) {
if ( class_exists( get_option( 'wp_webservice' ) ) ) {
$sms->to = array( get_option( 'wp_admin_mobile' ) );
$sms->msg = $final_text_report;
$sms->SendSMS();
}
}
}
}

View File

@@ -0,0 +1,223 @@
<?php
/**
* Class WP_Statistics_Shortcode
*/
class WP_Statistics_Shortcode {
/**
* @param $atts
*
* WP-Statistics shortcode is in the format of:
* [wpstatistics stat=xxx time=xxxx provider=xxxx format=xxxxxx id=xxx]
* Where:
* stat = the statistic you want.
* time = is the timeframe, strtotime() (http://php.net/manual/en/datetime.formats.php) will be used to calculate
* it. provider = the search provider to get stats on. format = i18n, english, none. id = the page/post id to get
* stats on.
*
* @return array|false|int|null|object|string|void
*/
static function shortcodes( $atts ) {
if ( ! is_array( $atts ) ) {
return;
}
if ( ! array_key_exists( 'stat', $atts ) ) {
return;
}
if ( ! array_key_exists( 'time', $atts ) ) {
$atts['time'] = null;
}
if ( ! array_key_exists( 'provider', $atts ) ) {
$atts['provider'] = 'all';
}
if ( ! array_key_exists( 'format', $atts ) ) {
$atts['format'] = null;
}
if ( ! array_key_exists( 'id', $atts ) ) {
$atts['id'] = - 1;
}
$formatnumber = array_key_exists( 'format', $atts );
switch ( $atts['stat'] ) {
case 'usersonline':
$result = wp_statistics_useronline();
break;
case 'visits':
$result = wp_statistics_visit( $atts['time'] );
break;
case 'visitors':
$result = wp_statistics_visitor( $atts['time'], null, true );
break;
case 'pagevisits':
$result = wp_statistics_pages( $atts['time'], null, $atts['id'] );
break;
case 'searches':
$result = wp_statistics_searchengine( $atts['provider'], $atts['time'] );
break;
case 'referrer':
$result = wp_statistics_referrer( $atts['time'] );
break;
case 'postcount':
$result = wp_statistics_countposts();
break;
case 'pagecount':
$result = wp_statistics_countpages();
break;
case 'commentcount':
$result = wp_statistics_countcomment();
break;
case 'spamcount':
$result = wp_statistics_countspam();
break;
case 'usercount':
$result = wp_statistics_countusers();
break;
case 'postaverage':
$result = wp_statistics_average_post();
break;
case 'commentaverage':
$result = wp_statistics_average_comment();
break;
case 'useraverage':
$result = wp_statistics_average_registeruser();
break;
case 'lpd':
$result = wp_statistics_lastpostdate();
$formatnumber = false;
break;
}
if ( $formatnumber ) {
switch ( strtolower( $atts['format'] ) ) {
case 'i18n':
$result = number_format_i18n( $result );
break;
case 'english':
$result = number_format( $result );
break;
}
}
return $result;
}
/**
*
*/
static function shortcake() {
// ShortCake support if loaded.
if ( function_exists( 'shortcode_ui_register_for_shortcode' ) ) {
$se_list = wp_statistics_searchengine_list();
$se_options = array( '' => 'None' );
foreach ( $se_list as $se ) {
$se_options[ $se['tag'] ] = $se['translated'];
}
shortcode_ui_register_for_shortcode(
'wpstatistics',
array(
// Display label. String. Required.
'label' => 'WP Statistics',
// Icon/image for shortcode. Optional. src or dashicons-$icon. Defaults to carrot.
'listItemImage' => '<img src="' .
WP_Statistics::$reg['plugin-url'] .
'assets/images/logo-250.png" width="128" height="128">',
// Available shortcode attributes and default values. Required. Array.
// Attribute model expects 'attr', 'type' and 'label'
// Supported field types: text, checkbox, textarea, radio, select, email, url, number, and date.
'attrs' => array(
array(
'label' => __( 'Statistic', 'wp-statistics' ),
'attr' => 'stat',
'type' => 'select',
'description' => __( 'Select the statistic you wish to display.', 'wp-statistics' ),
'value' => 'usersonline',
'options' => array(
'usersonline' => __( 'Online Users', 'wp-statistics' ),
'visits' => __( 'Visits', 'wp-statistics' ),
'visitors' => __( 'Visitors', 'wp-statistics' ),
'pagevisits' => __( 'Page Visits', 'wp-statistics' ),
'searches' => __( 'Searches', 'wp-statistics' ),
'postcount' => __( 'Post Count', 'wp-statistics' ),
'pagecount' => __( 'Page Count', 'wp-statistics' ),
'commentcount' => __( 'Comment Count', 'wp-statistics' ),
'spamcount' => __( 'Spam Count', 'wp-statistics' ),
'usercount' => __( 'User Count', 'wp-statistics' ),
'postaverage' => __( 'Post Average', 'wp-statistics' ),
'commentaverage' => __( 'Comment Average', 'wp-statistics' ),
'useraverage' => __( 'User Average', 'wp-statistics' ),
'lpd' => __( 'Last Post Date', 'wp-statistics' ),
'referrer' => __( 'Referrer', 'wp-statistics' ),
),
),
array(
'label' => __( 'Time Frame', 'wp-statistics' ),
'attr' => 'time',
'type' => 'url',
'description' => __(
'The time frame to get the statistic for, strtotime() (http://php.net/manual/en/datetime.formats.php) will be used to calculate it. Use "total" to get all recorded dates.',
'wp-statistics'
),
'meta' => array( 'size' => '10' ),
),
array(
'label' => __( 'Search Provider', 'wp-statistics' ),
'attr' => 'provider',
'type' => 'select',
'description' => __( 'The search provider to get statistics on.', 'wp-statistics' ),
'options' => $se_options,
),
array(
'label' => __( 'Number Format', 'wp-statistics' ),
'attr' => 'format',
'type' => 'select',
'description' => __(
'The format to display numbers in: i18n, english, none.',
'wp-statistics'
),
'value' => 'none',
'options' => array(
'none' => __( 'None', 'wp-statistics' ),
'english' => __( 'English', 'wp-statistics' ),
'i18n' => __( 'International', 'wp-statistics' ),
),
),
array(
'label' => __( 'Post/Page ID', 'wp-statistics' ),
'attr' => 'id',
'type' => 'number',
'description' => __( 'The post/page ID to get page statistics on.', 'wp-statistics' ),
'meta' => array( 'size' => '5' ),
),
),
)
);
}
}
}

View File

@@ -0,0 +1,150 @@
<?php
/**
* Class WP_Statistics_TinyMCE
*/
class WP_Statistics_TinyMCE {
/**
* Setup an TinyMCE action to close the notice on the overview page.
*/
public function __construct() {
// Add Filter TinyMce Editor
add_action( 'admin_head', array( $this, 'wp_statistic_add_my_tc_button' ) );
//Load Text Widget Button
add_action( 'admin_enqueue_scripts', array( $this, 'load_tinymcejs_widget_wp_admin_style' ) );
// Add TextLang
add_action( 'admin_footer-widgets.php', array( $this, 'my_post_edit_page_footer' ), 999 );
}
/*
* Language List Text Domain
*/
static public function lang() {
if ( ! class_exists( '_WP_Editors' ) ) {
require( ABSPATH . WPINC . '/class-wp-editor.php' );
}
$strings = array(
'insert' => __( 'WP Statistics Shortcodes', 'wp-statistics' ),
'stat' => __( 'Stat', 'wp-statistics' ),
'usersonline' => __( 'Online Users', 'wp-statistics' ),
'visits' => __( 'Visits', 'wp-statistics' ),
'visitors' => __( 'Visitors', 'wp-statistics' ),
'pagevisits' => __( 'Page Visits', 'wp-statistics' ),
'searches' => __( 'Searches', 'wp-statistics' ),
'postcount' => __( 'Post Count', 'wp-statistics' ),
'pagecount' => __( 'Page Count', 'wp-statistics' ),
'commentcount' => __( 'Comment Count', 'wp-statistics' ),
'spamcount' => __( 'Spam Count', 'wp-statistics' ),
'usercount' => __( 'User Count', 'wp-statistics' ),
'postaverage' => __( 'Post Average', 'wp-statistics' ),
'commentaverage' => __( 'Comment Average', 'wp-statistics' ),
'useraverage' => __( 'User Average', 'wp-statistics' ),
'lpd' => __( 'Last Post Date', 'wp-statistics' ),
'referrer' => __( 'Referrer', 'wp-statistics' ),
'help_stat' => __( 'The statistics you want, see the next table for available options.', 'wp-statistics' ),
'time' => __( 'Time', 'wp-statistics' ),
'se' => __( 'Select item ...', 'wp-statistics' ),
'today' => __( 'Today', 'wp-statistics' ),
'yesterday' => __( 'Yesterday', 'wp-statistics' ),
'week' => __( 'Week', 'wp-statistics' ),
'month' => __( 'Month', 'wp-statistics' ),
'year' => __( 'Year', 'wp-statistics' ),
'total' => __( 'Total', 'wp-statistics' ),
'help_time' => __( 'Is the time frame (time periods) for the statistic', 'wp-statistics' ),
'provider' => __( 'Provider', 'wp-statistics' ),
'help_provider' => __( 'The search provider to get statistics on.', 'wp-statistics' ),
'format' => __( 'Format', 'wp-statistics' ),
'help_format' => __( 'The format to display numbers in: i18n, english, none.', 'wp-statistics' ),
'id' => __( 'ID', 'wp-statistics' ),
'help_id' => __( 'The post/page ID to get page statistics on.', 'wp-statistics' ),
);
$locale = _WP_Editors::$mce_locale;
$translated = 'tinyMCE.addI18n("' . $locale . '.wp_statistic_tinymce_plugin", ' . json_encode( $strings ) . ");\n";
return array( 'locale' => $locale, 'translate' => $translated );
}
/*
* Add Filter TinyMCE
*/
public function wp_statistic_add_my_tc_button() {
global $typenow;
// check user permissions
if ( ! current_user_can( 'edit_posts' ) && ! current_user_can( 'edit_pages' ) ) {
return;
}
// verify the post type
if ( ! in_array( $typenow, array( 'post', 'page' ) ) ) {
return;
}
// check if WYSIWYG is enabled
if ( get_user_option( 'rich_editing' ) == 'true' ) {
add_filter( "mce_external_plugins", array( $this, 'wp_statistic_add_tinymce_plugin' ) );
add_filter( 'mce_buttons', array( $this, 'wp_statistic_register_my_tc_button' ) );
add_filter( 'mce_external_languages', array( $this, 'wp_statistic_tinymce_plugin_add_locale' ) );
}
}
/*
* Add Js Bottun to Editor
*/
public function wp_statistic_add_tinymce_plugin( $plugin_array ) {
$plugin_array['wp_statistic_tc_button'] = WP_Statistics::$reg['plugin-url'] . 'assets/js/tinymce.js';
return $plugin_array;
}
/*
* Push Button to TinyMCE Advance
*/
public function wp_statistic_register_my_tc_button( $buttons ) {
array_push( $buttons, "wp_statistic_tc_button" );
return $buttons;
}
/*
* Add Lang Text Domain
*/
public function wp_statistic_tinymce_plugin_add_locale( $locales ) {
$locales ['wp-statistic-tinymce-plugin'] = WP_Statistics::$reg['plugin-dir'] . 'includes/functions/tinymce.php';
return $locales;
}
/*
* Add Button For Text Widget
*/
public function load_tinymcejs_widget_wp_admin_style() {
global $pagenow;
if ( $pagenow == "widgets.php" ) {
wp_enqueue_script( 'add_wp_statistic_button_for_widget_text', WP_Statistics::$reg['plugin-url'] . 'assets/js/tinymce.js' );
}
}
/*
* Add Lang for Text Widget
*/
public function my_post_edit_page_footer() {
echo '
<script type="text/javascript">
jQuery( document ).on( \'tinymce-editor-setup\', function( event, editor ) {
editor.settings.toolbar1 += \',wp_statistic_tc_button\';
});
';
$lang = WP_Statistics_TinyMCE::lang();
echo $lang['translate'];
echo '
tinyMCEPreInit.load_ext("' . rtrim( WP_Statistics::$reg['plugin-url'], "/" ) . '", "' . $lang['locale'] . '");
</script>
';
}
}

View File

@@ -0,0 +1,58 @@
<?php
/**
* Class WP_Statistics_Uninstall
*/
class WP_Statistics_Uninstall {
/**
* WP_Statistics_Uninstall constructor.
*/
function __construct() {
if ( is_admin() ) {
global $WP_Statistics;
// Handle multi site implementations
if ( is_multisite() ) {
// Loop through each of the sites.
$sites = $WP_Statistics->get_wp_sites_list();
foreach ( $sites as $blog_id ) {
switch_to_blog( $blog_id );
$this->wp_statistics_site_removal();
}
restore_current_blog();
} else {
$this->wp_statistics_site_removal();
}
// Make sure we don't try and remove the data more than once.
update_option( 'wp_statistics_removal', 'done' );
}
}
/**
* Removes database options, user meta keys & tables
*/
public function wp_statistics_site_removal() {
global $wpdb;
// Delete the options from the WordPress options table.
delete_option( 'wp_statistics' );
delete_option( 'wp_statistics_db_version' );
delete_option( 'wp_statistics_plugin_version' );
delete_option( 'wp_statistics_overview_page_ads' );
// Delete the transients.
delete_transient( 'wps_top_referring' );
delete_transient( 'wps_excluded_hostname_to_ip_cache' );
// Delete the user options.
$wpdb->query( "DELETE FROM {$wpdb->prefix}usermeta WHERE meta_key LIKE 'wp_statistics%'" );
// Drop the tables
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}statistics_useronline, {$wpdb->prefix}statistics_visit, {$wpdb->prefix}statistics_visitor, {$wpdb->prefix}statistics_exclusions, {$wpdb->prefix}statistics_pages, {$wpdb->prefix}statistics_historical, {$wpdb->prefix}statistics_search" );
}
}

View File

@@ -0,0 +1,299 @@
<?php
/**
* Class WP_Statistics_Updates
*/
class WP_Statistics_Updates {
//List Geo ip Library
public static $geoip = array(
'country' => array(
'cdn' => 'http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.mmdb.gz',
'github' => 'https://raw.githubusercontent.com/wp-statistics/GeoLite2-Country/master/GeoLite2-Country.mmdb.gz',
'file' => 'GeoLite2-Country',
'opt' => 'geoip'
),
'city' => array(
'cdn' => 'http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz',
'github' => 'https://raw.githubusercontent.com/wp-statistics/GeoLite2-City/master/GeoLite2-City.mmdb.gz',
'file' => 'GeoLite2-City',
'opt' => 'geoip_city'
)
);
/**
* Update option process.
*/
static function do_upgrade() {
}
/**
* This function downloads the GeoIP database from MaxMind.
*
* @param $pack
* @param string $type
*
* @return string
*/
static function download_geoip( $pack, $type = "enable" ) {
GLOBAL $WP_Statistics;
//Create Empty Return Function
$result["status"] = false;
// We need the download_url() function, it should exists on virtually all installs of PHP, but if it doesn't for some reason, bail out.
if ( ! function_exists( 'download_url' ) ) {
include( ABSPATH . 'wp-admin/includes/file.php' );
}
// We need the wp_generate_password() function.
if ( ! function_exists( 'wp_generate_password' ) ) {
include( ABSPATH . 'wp-includes/pluggable.php' );
}
// We need the gzopen() function, it should exists on virtually all installs of PHP, but if it doesn't for some reason, bail out.
// Also stop trying to update the database as it just won't work :)
if ( false === function_exists( 'gzopen' ) ) {
if ( $type == "enable" ) {
$WP_Statistics->update_option( WP_Statistics_Updates::$geoip[ $pack ]['opt'], '' );
}
$result["notice"] = __( 'Error the gzopen() function do not exist!', 'wp-statistics' );
WP_Statistics_Admin_Pages::set_admin_notice( $result["notice"], $type = 'error' );
return $result;
}
// If GeoIP is disabled, bail out.
if ( $type == "update" and $WP_Statistics->get_option( WP_Statistics_Updates::$geoip[ $pack ]['opt'] ) == '' ) {
return '';
}
// This is the location of the file to download.
$download_url = WP_Statistics_Updates::$geoip[ $pack ]['cdn'];
$response = wp_remote_get( $download_url );
// Change download url if the maxmind.com doesn't response.
if ( wp_remote_retrieve_response_code( $response ) != '200' ) {
$download_url = WP_Statistics_Updates::$geoip[ $pack ]['github'];
}
// Get the upload directory from WordPress.
$upload_dir = wp_upload_dir();
// Create a variable with the name of the database file to download.
$DBFile = $upload_dir['basedir'] . '/wp-statistics/' . WP_Statistics_Updates::$geoip[ $pack ]['file'] . '.mmdb';
// Check to see if the subdirectory we're going to upload to exists, if not create it.
if ( ! file_exists( $upload_dir['basedir'] . '/wp-statistics' ) ) {
if ( ! @mkdir( $upload_dir['basedir'] . '/wp-statistics', 0755 ) ) {
if ( $type == "enable" ) {
$WP_Statistics->update_option( WP_Statistics_Updates::$geoip[ $pack ]['opt'], '' );
}
$result["notice"] = sprintf( __( 'Error creating GeoIP database directory, make sure your web server has permissions to create directories in: %s', 'wp-statistics' ), $upload_dir['basedir'] );
WP_Statistics_Admin_Pages::set_admin_notice( $result["notice"], $type = 'error' );
return $result;
}
}
if ( ! is_writable( $upload_dir['basedir'] . '/wp-statistics' ) ) {
if ( $type == "enable" ) {
$WP_Statistics->update_option( WP_Statistics_Updates::$geoip[ $pack ]['opt'], '' );
}
$result["notice"] = sprintf( __( 'Error setting permissions of the GeoIP database directory, make sure your web server has permissions to write to directories in : %s', 'wp-statistics' ),
$upload_dir['basedir']
);
WP_Statistics_Admin_Pages::set_admin_notice( $result["notice"], $type = 'error' );
return $result;
}
// Download the file from MaxMind, this places it in a temporary location.
$TempFile = download_url( $download_url );
// If we failed, through a message, otherwise proceed.
if ( is_wp_error( $TempFile ) ) {
if ( $type == "enable" ) {
$WP_Statistics->update_option( WP_Statistics_Updates::$geoip[ $pack ]['opt'], '' );
}
$result["notice"] = sprintf( __( 'Error downloading GeoIP database from: %s - %s', 'wp-statistics' ), $download_url, $TempFile->get_error_message() );
WP_Statistics_Admin_Pages::set_admin_notice( $result["notice"], $type = 'error' );
} else {
// Open the downloaded file to unzip it.
$ZipHandle = gzopen( $TempFile, 'rb' );
// Create th new file to unzip to.
$DBfh = fopen( $DBFile, 'wb' );
// If we failed to open the downloaded file, through an error and remove the temporary file. Otherwise do the actual unzip.
if ( ! $ZipHandle ) {
if ( $type == "enable" ) {
$WP_Statistics->update_option( WP_Statistics_Updates::$geoip[ $pack ]['opt'], '' );
}
$result["notice"] = sprintf(
__( 'Error could not open downloaded GeoIP database for reading: %s', 'wp-statistics' ),
$TempFile
);
WP_Statistics_Admin_Pages::set_admin_notice( $result["notice"], $type = 'error' );
unlink( $TempFile );
} else {
// If we failed to open the new file, throw and error and remove the temporary file. Otherwise actually do the unzip.
if ( ! $DBfh ) {
if ( $type == "enable" ) {
$WP_Statistics->update_option( WP_Statistics_Updates::$geoip[ $pack ]['opt'], '' );
}
$result["notice"] = sprintf( __( 'Error could not open destination GeoIP database for writing %s', 'wp-statistics' ), $DBFile );
WP_Statistics_Admin_Pages::set_admin_notice( $result["notice"], $type = 'error' );
unlink( $TempFile );
} else {
while ( ( $data = gzread( $ZipHandle, 4096 ) ) != false ) {
fwrite( $DBfh, $data );
}
// Close the files.
gzclose( $ZipHandle );
fclose( $DBfh );
// Delete the temporary file.
unlink( $TempFile );
// Display the success message.
$result["status"] = true;
$result["notice"] = "<div class='updated settings-error'><p><strong>" . __( 'GeoIP Database updated successfully!', 'wp-statistics' ) . "</strong></p></div>";
// Update the options to reflect the new download.
if ( $type == "update" ) {
$WP_Statistics->update_option( 'last_geoip_dl', time() );
$WP_Statistics->update_option( 'update_geoip', false );
}
// Populate any missing GeoIP information if the user has selected the option.
if ( $pack == "country" ) {
if ( $WP_Statistics->get_option( 'geoip' ) &&
wp_statistics_geoip_supported() &&
$WP_Statistics->get_option( 'auto_pop' )
) {
WP_Statistics_Updates::populate_geoip_info();
}
}
}
}
}
if ( $WP_Statistics->get_option( 'geoip_report' ) == true ) {
$blogname = get_bloginfo( 'name' );
$blogemail = get_bloginfo( 'admin_email' );
$headers[] = "From: $blogname <$blogemail>";
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/html; charset=utf-8";
if ( $WP_Statistics->get_option( 'email_list' ) == '' ) {
$WP_Statistics->update_option( 'email_list', $blogemail );
}
wp_mail( $WP_Statistics->get_option( 'email_list' ), __( 'GeoIP update on', 'wp-statistics' ) . ' ' . WP_Statistics_Admin_Pages::sanitize_mail_subject( $blogname ), $result['notice'], $headers );
}
// All of the messages displayed above are stored in a string, now it's time to actually output the messages.
return $result;
}
/**
* Downloads the referrer spam database from https://github.com/matomo-org/referrer-spam-blacklist.
* @return string
*/
static function download_referrerspam() {
global $WP_Statistics;
// If referrer spam is disabled, bail out.
if ( $WP_Statistics->get_option( 'referrerspam' ) == false ) {
return '';
}
// This is the location of the file to download.
$download_url = 'https://raw.githubusercontent.com/matomo-org/referrer-spam-blacklist/master/spammers.txt';
// Download the file from MaxMind, this places it in a temporary location.
$response = wp_remote_get( $download_url, array( 'timeout' => 30 ) );
if ( is_wp_error( $response ) ) {
return false;
}
$referrerspamlist = wp_remote_retrieve_body( $response );
if ( is_wp_error( $referrerspamlist ) ) {
return false;
}
if ( $referrerspamlist != '' || $WP_Statistics->get_option( 'referrerspamlist' ) != '' ) {
$WP_Statistics->update_option( 'referrerspamlist', $referrerspamlist );
}
return true;
}
/**
* Populate GeoIP information in to the database.
* It is used in two different parts of the plugin;
* When a user manual requests the update to happen and after a new GeoIP database has been download
* (if the option is selected).
*
* @return string
*/
static function populate_geoip_info() {
global $wpdb, $WP_Statistics;
// Find all rows in the table that currently don't have GeoIP info or have an unknown ('000') location.
$result = $wpdb->get_results( "SELECT id,ip FROM `{$wpdb->prefix}statistics_visitor` WHERE location = '' or location = '000' or location IS NULL" );
// Try create a new reader instance.
$reader = false;
if ( $WP_Statistics->get_option( 'geoip' ) ) {
$reader = $WP_Statistics::geoip_loader( 'country' );
}
if ( $reader === false ) {
$text_error = __( 'Unable to load the GeoIP database, make sure you have downloaded it in the settings page.', 'wp-statistics' );
WP_Statistics_Admin_Pages::set_admin_notice( $text_error, $type = 'error' );
}
$count = 0;
// Loop through all the missing rows and update them if we find a location for them.
foreach ( $result as $item ) {
$count ++;
// If the IP address is only a hash, don't bother updating the record.
if ( substr( $item->ip, 0, 6 ) != '#hash#' and $reader != false ) {
try {
$record = $reader->country( $item->ip );
$location = $record->country->isoCode;
if ( $location == "" ) {
$location = "000";
}
} catch ( Exception $e ) {
$location = "000";
}
// Update the row in the database.
$wpdb->update(
$wpdb->prefix . "statistics_visitor",
array( 'location' => $location ),
array( 'id' => $item->id )
);
}
}
return "<div class='updated settings-error'><p><strong>" . sprintf( __( 'Updated %s GeoIP records in the visitors database.', 'wp-statistics' ), $count ) . "</strong></p></div>";
}
}

View File

@@ -0,0 +1,102 @@
<?php
/**
* Class WP_Statistics_Welcome
*/
class WP_Statistics_Welcome {
/**
* Initial
*/
public static function init() {
global $WP_Statistics;
if ( $WP_Statistics->get_option( 'show_welcome_page', false ) and ( strpos( $_SERVER['REQUEST_URI'], '/wp-admin/index.php' ) !== false or ( isset( $_GET['page'] ) and $_GET['page'] == 'wps_overview_page' ) ) ) {
// Disable show welcome page
$WP_Statistics->update_option( 'first_show_welcome_page', true );
$WP_Statistics->update_option( 'show_welcome_page', false );
// Redirect to welcome page
wp_redirect( WP_Statistics_Admin_Pages::admin_url( 'wps_welcome' ) );
}
if ( ! $WP_Statistics->get_option( 'first_show_welcome_page', false ) ) {
$WP_Statistics->update_option( 'show_welcome_page', true );
}
}
/**
* Register menu
*/
public static function menu() {
add_submenu_page( __( 'WP-Statistics Welcome', 'wp-statistics' ), __( 'WP-Statistics Welcome', 'wp-statistics' ), __( 'WP-Statistics Welcome', 'wp-statistics' ), 'administrator', 'wps_welcome', 'WP_Statistics_Welcome::page_callback' );
}
/**
* Welcome page
*/
public static function page_callback() {
// Create Default Variable
$error = null;
$plugins = array();
// Check List Plugins if in Plugins Tab
if ( isset( $_GET['tab'] ) and $_GET['tab'] == "addons" ) {
$response = wp_remote_get( 'https://wp-statistics.com/wp-json/plugin/addons' );
$response_code = wp_remote_retrieve_response_code( $response );
if ( is_wp_error( $response ) ) {
$error = $response->get_error_message();
} else {
if ( $response_code == '200' ) {
$plugins = json_decode( $response['body'] );
} else {
$error = $response['body'];
}
}
}
include( WP_Statistics::$reg['plugin-dir'] . "includes/templates/welcome.php" );
}
/**
* @param $upgrader_object
* @param $options
*/
public static function do_welcome( $upgrader_object, $options ) {
$current_plugin_path_name = 'wp-statistics/wp-statistics.php';
if ( isset( $options['action'] ) and $options['action'] == 'update' and isset( $options['type'] ) and $options['type'] == 'plugin' and isset( $options['plugins'] ) ) {
foreach ( $options['plugins'] as $each_plugin ) {
if ( $each_plugin == $current_plugin_path_name ) {
global $WP_Statistics;
// Enable welcome page in database
$WP_Statistics->update_option( 'show_welcome_page', true );
// Run the upgrader
WP_Statistics_Updates::do_upgrade();
}
}
}
}
/**
* Show change log
*/
public static function show_change_log() {
$response = wp_remote_get( 'https://api.github.com/repos/wp-statistics/wp-statistics/releases/latest' );
// Check response
if ( is_wp_error( $response ) ) {
return;
}
$response_code = wp_remote_retrieve_response_code( $response );
if ( $response_code == '200' ) {
$data = json_decode( $response['body'] );
$Parsedown = new Parsedown();
echo $Parsedown->text( nl2br( $data->body ) );
}
}
}

View File

@@ -0,0 +1,435 @@
<?php
class WP_Statistics_Widget extends WP_Widget {
/**
* Sets up the widgets name etc
*/
public function __construct() {
parent::__construct(
'WP_Statistics_Widget', // Base ID
__( 'Statistics', 'wp-statistics' ), // Name
array( 'description' => __( 'Show site stats in sidebar.', 'wp-statistics' ) ) // Args
);
}
/**
* Outputs the content of the widget
*
* @param array $args
* @param array $instance
*/
public function widget( $args, $instance ) {
global $WP_Statistics;
extract( $args );
$widget_options = $WP_Statistics->get_option( 'widget' );
echo $before_widget;
echo $before_title . $widget_options['name_widget'] . $after_title;
echo '<ul>';
if ( $widget_options['useronline_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Online Users', 'wp-statistics' ) . ': </label>';
echo number_format_i18n( wp_statistics_useronline() );
echo '</li>';
}
if ( $widget_options['tvisit_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Today\'s Visits', 'wp-statistics' ) . ': </label>';
echo number_format_i18n( wp_statistics_visit( 'today' ) );
echo '</li>';
}
if ( $widget_options['tvisitor_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Today\'s Visitors', 'wp-statistics' ) . ': </label>';
echo number_format_i18n( wp_statistics_visitor( 'today', null, true ) );
echo '</li>';
}
if ( $widget_options['yvisit_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Yesterday\'s Visits', 'wp-statistics' ) . ': </label>';
echo number_format_i18n( wp_statistics_visit( 'yesterday' ) );
echo '</li>';
}
if ( $widget_options['yvisitor_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Yesterday\'s Visitors', 'wp-statistics' ) . ': </label>';
echo number_format_i18n( wp_statistics_visitor( 'yesterday', null, true ) );
echo '</li>';
}
if ( $widget_options['wvisit_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Last 7 Days Visits', 'wp-statistics' ) . ': </label>';
echo number_format_i18n( wp_statistics_visit( 'week' ) );
echo '</li>';
}
if ( $widget_options['mvisit_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Last 30 Days Visits', 'wp-statistics' ) . ': </label>';
echo number_format_i18n( wp_statistics_visit( 'month' ) );
echo '</li>';
}
if ( $widget_options['ysvisit_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Last 365 Days Visits', 'wp-statistics' ) . ': </label>';
echo number_format_i18n( wp_statistics_visit( 'year' ) );
echo '</li>';
}
if ( $widget_options['ttvisit_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Total Visits', 'wp-statistics' ) . ': </label>';
echo number_format_i18n( wp_statistics_visit( 'total' ) );
echo '</li>';
}
if ( $widget_options['ttvisitor_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Total Visitors', 'wp-statistics' ) . ': </label>';
echo number_format_i18n( wp_statistics_visitor( 'total', null, true ) );
echo '</li>';
}
if ( $widget_options['tpviews_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Total Page Views', 'wp-statistics' ) . ': </label>';
echo number_format_i18n( wp_statistics_pages( 'total' ) );
echo '</li>';
}
if ( $widget_options['ser_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Search Engine Referrals', 'wp-statistics' ) . ': </label>';
echo number_format_i18n( wp_statistics_searchengine( $widget_options['select_se'] ) );
echo '</li>';
}
if ( $widget_options['tp_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Total Posts', 'wp-statistics' ) . ': </label>';
echo number_format_i18n( wp_statistics_countposts() );
echo '</li>';
}
if ( $widget_options['tpg_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Total Pages', 'wp-statistics' ) . ': </label>';
echo number_format_i18n( wp_statistics_countpages() );
echo '</li>';
}
if ( $widget_options['tc_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Total Comments', 'wp-statistics' ) . ': </label>';
echo number_format_i18n( wp_statistics_countcomment() );
echo '</li>';
}
if ( $widget_options['ts_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Total Spams', 'wp-statistics' ) . ': </label>';
echo wp_statistics_countspam();
echo '</li>';
}
if ( $widget_options['tu_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Total Users', 'wp-statistics' ) . ': </label>';
echo number_format_i18n( wp_statistics_countusers() );
echo '</li>';
}
if ( $widget_options['ap_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Post Average', 'wp-statistics' ) . ': </label>';
echo number_format_i18n( wp_statistics_average_post() );
echo '</li>';
}
if ( $widget_options['ac_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Comment Average', 'wp-statistics' ) . ': </label>';
echo number_format_i18n( wp_statistics_average_comment() );
echo '</li>';
}
if ( $widget_options['au_widget'] ) {
echo '<li>';
echo '<label>' . __( 'User Average', 'wp-statistics' ) . ': </label>';
echo number_format_i18n( wp_statistics_average_registeruser() );
echo '</li>';
}
if ( $widget_options['lpd_widget'] ) {
echo '<li>';
echo '<label>' . __( 'Last Post Date', 'wp-statistics' ) . ': </label>';
echo wp_statistics_lastpostdate();
echo '</li>';
}
echo '</ul>';
echo $after_widget;
}
/**
* Processing widget options on save
*
* @param array $new_instance The new options
* @param array $old_instance The previous options
*
* @return array
*/
public function update( $new_instance, $old_instance ) {
GLOBAL $WP_Statistics;
if ( array_key_exists( 'wp_statistics_control_widget_submit', $_POST ) ) {
$keys = array(
'name_widget' => 'name_widget',
'useronline_widget' => 'useronline_widget',
'tvisit_widget' => 'tvisit_widget',
'tvisitor_widget' => 'tvisitor_widget',
'yvisit_widget' => 'yvisit_widget',
'yvisitor_widget' => 'yvisitor_widget',
'wvisit_widget' => 'wvisit_widget',
'mvisit_widget' => 'mvisit_widget',
'ysvisit_widget' => 'ysvisit_widget',
'ttvisit_widget' => 'ttvisit_widget',
'ttvisitor_widget' => 'ttvisitor_widget',
'tpviews_widget' => 'tpviews_widget',
'ser_widget' => 'ser_widget',
'select_se' => 'select_se',
'tp_widget' => 'tp_widget',
'tpg_widget' => 'tpg_widget',
'tc_widget' => 'tc_widget',
'ts_widget' => 'ts_widget',
'tu_widget' => 'tu_widget',
'ap_widget' => 'ap_widget',
'ac_widget' => 'ac_widget',
'au_widget' => 'au_widget',
'lpd_widget' => 'lpd_widget',
'select_lps' => 'select_lps',
);
foreach ( $keys as $key => $post ) {
if ( array_key_exists( $post, $_POST ) ) {
$widget_options[ $key ] = $_POST[ $post ];
} else {
$widget_options[ $key ] = '';
}
}
$WP_Statistics->update_option( 'widget', $widget_options );
}
return array();
}
/**
* Outputs the options form on admin
*
* @param array $instance The widget options
*
* @return string|void
*/
public function form( $instance ) {
GLOBAL $WP_Statistics;
$widget_options = $WP_Statistics->get_option( 'widget' );
?>
<p>
<label for="name_widget"><?php _e( 'Name', 'wp-statistics' ); ?>:
<input id="name_widget" name="name_widget" type="text"
value="<?php echo $widget_options['name_widget']; ?>"/>
</label>
</p>
<?php _e( 'Items', 'wp-statistics' ); ?>:<br/>
<ul>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'useronline_widget' ) ); ?>" name="useronline_widget" <?php checked(
'on',
$widget_options['useronline_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'useronline_widget' ) ); ?>"><?php _e( 'Online Users', 'wp-statistics' ); ?></label>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'tvisit_widget' ) ); ?>" name="tvisit_widget" <?php checked(
'on',
$widget_options['tvisit_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'tvisit_widget' ) ); ?>"><?php _e( 'Today\'s Visits', 'wp-statistics' ); ?></label>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'tvisitor_widget' ) ); ?>" name="tvisitor_widget" <?php checked(
'on',
$widget_options['tvisitor_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'tvisitor_widget' ) ); ?>"><?php _e( 'Today\'s Visitors', 'wp-statistics' ); ?></label>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'yvisit_widget' ) ); ?>" name="yvisit_widget" <?php checked(
'on',
$widget_options['yvisit_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'yvisit_widget' ) ); ?>"><?php _e( 'Yesterday\'s Visits', 'wp-statistics' ); ?></label>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'yvisitor_widget' ) ); ?>" name="yvisitor_widget" <?php checked(
'on',
$widget_options['yvisitor_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'yvisitor_widget' ) ); ?>"><?php _e( 'Yesterday\'s Visitors', 'wp-statistics' ); ?></label>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'wvisit_widget' ) ); ?>" name="wvisit_widget" <?php checked(
'on',
$widget_options['wvisit_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'wvisit_widget' ) ); ?>"><?php _e( 'Last 7 Days Visits', 'wp-statistics' ); ?></label>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'mvisit_widget' ) ); ?>" name="mvisit_widget" <?php checked(
'on',
$widget_options['mvisit_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'mvisit_widget' ) ); ?>"><?php _e( 'Last 30 Days Visits', 'wp-statistics' ); ?></label>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'ysvisit_widget' ) ); ?>" name="ysvisit_widget" <?php checked(
'on',
$widget_options['ysvisit_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'ysvisit_widget' ) ); ?>"><?php _e( 'Last 365 Days Visits', 'wp-statistics' ); ?></label>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'ttvisit_widget' ) ); ?>" name="ttvisit_widget" <?php checked(
'on',
$widget_options['ttvisit_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'ttvisit_widget' ) ); ?>"><?php _e( 'Total Visits', 'wp-statistics' ); ?></label>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'ttvisitor_widget' ) ); ?>" name="ttvisitor_widget" <?php checked(
'on',
$widget_options['ttvisitor_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'ttvisitor_widget' ) ); ?>"><?php _e( 'Total Visitors', 'wp-statistics' ); ?></label>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'tpviews_widget' ) ); ?>" name="tpviews_widget" <?php checked(
'on',
$widget_options['tpviews_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'tpviews_widget' ) ); ?>"><?php _e( 'Total Page Views', 'wp-statistics' ); ?></label>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'ser_widget' ) ); ?>" class="ser_widget" name="ser_widget" <?php checked(
'on',
$widget_options['ser_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'ser_widget' ) ); ?>"><?php _e( 'Search Engine Referrals', 'wp-statistics' ); ?></label>
<p id="ser_option" style="<?php if ( ! $widget_options['ser_widget'] ) {
echo "display: none;";
} ?>">
<?php _e( 'Select type of search engine', 'wp-statistics' ); ?>:<br/>
<?php
$search_engines = wp_statistics_searchengine_list();
foreach ( $search_engines as $se ) {
echo ' <input type="radio" id="select_' .
$se['tag'] .
'" name="select_se" value="' .
$se['tag'] .
'" ';
checked( $se['tag'], $widget_options['select_se'] );
echo "/>\n";
echo ' <label for="' . $se['name'] . '">' . $se['translated'] . "</label>\n";
echo "\n";
}
?>
<input type="radio" id="select_all" name="select_se" value="all" <?php checked(
'all',
$widget_options['select_se']
); ?>/>
<label for="select_all"><?php _e( 'All', 'wp-statistics' ); ?></label>
</p>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'tp_widget' ) ); ?>" name="tp_widget" <?php checked(
'on',
$widget_options['tp_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'tp_widget' ) ); ?>"><?php _e( 'Total Posts', 'wp-statistics' ); ?></label>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'tpg_widget' ) ); ?>" name="tpg_widget" <?php checked(
'on',
$widget_options['tpg_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'tpg_widget' ) ); ?>"><?php _e( 'Total Pages', 'wp-statistics' ); ?></label>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'tc_widget' ) ); ?>" name="tc_widget" <?php checked(
'on',
$widget_options['tc_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'tc_widget' ) ); ?>"><?php _e( 'Total Comments', 'wp-statistics' ); ?></label>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'ts_widget' ) ); ?>" name="ts_widget" <?php checked(
'on',
$widget_options['ts_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'ts_widget' ) ); ?>"><?php _e( 'Total Spams', 'wp-statistics' ); ?></label>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'tu_widget' ) ); ?>" name="tu_widget" <?php checked(
'on',
$widget_options['tu_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'tu_widget' ) ); ?>"><?php _e( 'Total Users', 'wp-statistics' ); ?></label>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'ap_widget' ) ); ?>" name="ap_widget" <?php checked(
'on',
$widget_options['ap_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'ap_widget' ) ); ?>"><?php _e( 'Post Average', 'wp-statistics' ); ?></label>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'ac_widget' ) ); ?>" name="ac_widget" <?php checked(
'on',
$widget_options['ac_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'ac_widget' ) ); ?>"><?php _e( 'Comment Average', 'wp-statistics' ); ?></label>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'au_widget' ) ); ?>" name="au_widget" <?php checked(
'on',
$widget_options['au_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'au_widget' ) ); ?>"><?php _e( 'User Average', 'wp-statistics' ); ?></label>
</li>
<li>
<input type="checkbox" id="<?php echo esc_attr( $this->get_field_id( 'lpd_widget' ) ); ?>" class="lpd_widget" name="lpd_widget" <?php checked(
'on',
$widget_options['lpd_widget']
); ?>/>
<label for="<?php echo esc_attr( $this->get_field_id( 'lpd_widget' ) ); ?>"><?php _e( 'Last Post Date', 'wp-statistics' ); ?></label>
</li>
</ul>
<input type="hidden" id="<?php echo esc_attr( $this->get_field_id( 'wp_statistics_control_widget_submit' ) ); ?>" name="wp_statistics_control_widget_submit"
value="1"/>
<?php
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,2 @@
Please add "WP_Statistics_" before any class name
This is for an internal rule to load classes fast!