\r\n";
$email_confirmation = wp_mail( $email_address, $subject, $message, $headers );
remove_filter( 'wp_mail_content_type', 'nsp_set_mail_content_type' );
return $email_confirmation;
}
/**
* Mail notificatiom deactivate
*/
function nsp_mail_notification_deactivate() {
wp_clear_scheduled_hook( 'nsp_mail_notification' );
}
// Hook mail publi.
add_action( 'nsp_mail_notification', 'nsp_stat_by_email' );
/**
* Add Settings link to plugins page
* added by cHab
*
* @param string $links the links.
* @param string $file the file.
* @return the link.
*/
function nsp_add_settings_link( $links, $file ) {
if ( plugin_basename( __FILE__ ) !== $file ) {
return $links;
}
$settings_link = '' . __( 'Settings', 'newstatpress' ) . '';
array_unshift( $links, $settings_link );
return $links;
}
add_filter( 'plugin_action_links', 'nsp_add_settings_link', 10, 2 );
/**TODO useful or not????
* PHP 4 compatible mb_substr function
* (taken in statpress-visitors)
*
* @param string $str the string.
* @param int $x x value.
* @param int $y y value.
* @return the substring.
*/
function nsp_my_substr( $str, $x, $y = 0 ) {
if ( 0 == $y ) {
$y = strlen( $str ) - $x;
}
if ( function_exists( 'mb_substr' ) ) {
return mb_substr( $str, $x, $y );
} else {
return substr( $str, $x, $y );
}
}
/**
* Decode the given url
*
* @param string $out_url the given url to decode.
* @return the decoded url.
****************************************/
function nsp_decode_url( $out_url ) {
$out_url = filter_var( $out_url, FILTER_SANITIZE_URL );
if ( '' === $out_url ) {
$out_url = __( 'Page', 'newstatpress' ) . ': Home'; }
if ( substr( $out_url, 0, 4 ) === 'cat=' ) {
$out_url = __( 'Category', 'newstatpress' ) . ': ' . get_cat_name( substr( $out_url, 4 ) ); }
if ( substr( $out_url, 0, 2 ) === 'm=' ) {
$out_url = __( 'Calendar', 'newstatpress' ) . ': ' . substr( $out_url, 6, 2 ) . '/' . substr( $out_url, 2, 4 ); }
if ( substr( $out_url, 0, 2 ) === 's=' ) {
$out_url = __( 'Search', 'newstatpress' ) . ': ' . substr( $out_url, 2 ); }
if ( substr( $out_url, 0, 2 ) === 'p=' ) {
$sub_out = substr( $out_url, 2 );
$post_id_7 = get_post( $sub_out, ARRAY_A );
$out_url = $post_id_7['post_title'];
}
if ( substr( $out_url, 0, 8 ) === 'page_id=' ) {
$sub_out = substr( $out_url, 8 );
$post_id_7 = get_page( $sub_out, ARRAY_A );
$out_url = __( 'Page', 'newstatpress' ) . ': ' . $post_id_7['post_title'];
}
return $out_url;
}
/**
* Get url
*
* @retrun the url.
*/
function nsp_url() {
$url_requested = ( isset( $_SERVER['QUERY_STRING'] ) ? filter_var( wp_unslash( $_SERVER['QUERY_STRING'] ), FILTER_SANITIZE_URL ) : '' );
if ( '' === $url_requested ) { // SEO problem!
$url_requested = ( isset( $_SERVER['REQUEST_URI'] ) ? filter_var( wp_unslash( $_SERVER['REQUEST_URI'] ), FILTER_SANITIZE_URL ) : '' );
}
if ( substr( $url_requested, 0, 2 ) === '/?' ) {
$url_requested = substr( $url_requested, 2 ); }
if ( '/' === $url_requested ) {
$url_requested = ''; }
// sanitize urldecode.
$url_requested = filter_var( $url_requested, FILTER_SANITIZE_URL );
return $url_requested;
}
/**
* Convert data us to default format di WordPress
*
* @param string $dt date to convert.
* @return converted data.
****************************************************/
function nsp_hdate( $dt = '00000000' ) {
return mysql2date( get_option( 'date_format' ), substr( $dt, 0, 4 ) . '-' . substr( $dt, 4, 2 ) . '-' . substr( $dt, 6, 2 ) );
}
/**
* Get newstatpress_hdate
*
* @param string $dt the date.
* @return the hdate.
*/
function newstatpress_hdate( $dt = '00000000' ) {
return mysql2date( get_option( 'date_format' ), nsp_my_substr( $dt, 0, 4 ) . '-' . nsp_my_substr( $dt, 4, 2 ) . '-' . nsp_my_substr( $dt, 6, 2 ) );
}
// ---------------------------------------------------------------------------
// GET DATA from visitors Functions
// ---------------------------------------------------------------------------
/**TODO clean $accepted
* Extracts the accepted language from browser headers
*
* @param string $accepted not used.
*/
function nsp_get_language( $accepted ) {
if ( isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) {
// Capture up to the first delimiter (, found in Safari).
preg_match( '/([^,;]*)/', sanitize_text_field( wp_unslash( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ), $array_languages );
// Fix some codes, the correct syntax is with minus (-) not underscore (_).
return str_replace( '_', '-', strtolower( $array_languages[0] ) );
}
return 'xx'; // Indeterminable language.
}
/**
* Get query pairs
*
* @param string $url the url.
* @return the pairs.
*/
function nsp_get_query_pairs( $url ) {
$parsed_url = wp_parse_url( $url );
$tab = wp_parse_url( $url );
$host = $tab['host'];
if ( key_exists( 'query', $tab ) ) {
$query = $tab['query'];
return explode( '&', $query );
} else {
return null;}
}
/**
* Get OS from the given argument
*
* @param string $arg the argument to parse for OS.
* @return the OS find in configuration file.
*******************************************/
function nsp_get_os( $arg ) {
global $newstatpress_dir;
$arg = str_replace( ' ', '', $arg );
$lines = file( $newstatpress_dir . '/def/os.dat' );
foreach ( $lines as $line_num => $os ) {
list($nome_os,$id_os) = explode( '|', $os );
if ( strpos( $arg, $id_os ) === false ) {
continue;
}
return $nome_os; // fount.
}
return '';
}
/**
* Get OS logo from the given argument
*
* @param string $arg the argument to parse for OS.
* @return the OS find in configuration file.
*******************************************/
function nsp_get_os_img( $arg ) {
global $newstatpress_dir;
$lines = file( $newstatpress_dir . '/def/os.dat' );
foreach ( $lines as $line_num => $os ) {
list($name_os,$id_os,$img_os) = explode( '|', $os );
if ( strcmp( $name_os, $arg ) == 0 ) {
return $img_os;
}
}
return '';
}
/**
* Get Browser from the given argument
*
* @param string $arg the argument to parse for Brower.
* @return the Browser find in configuration file.
************************************************/
function nsp_get_browser( $arg ) {
global $newstatpress_dir;
$arg = str_replace( ' ', '', $arg );
$lines = file( $newstatpress_dir . '/def/browser.dat' );
foreach ( $lines as $line_num => $browser ) {
list($nome,$id) = explode( '|', $browser );
if ( strpos( $arg, $id ) === false ) {
continue;
}
return $nome; // fount.
}
return '';
}
/**
* Get Browser from the given argument
*
* @param string $arg the argument to parse for Brower.
* @return the Browser find in configuration file.
************************************************/
function nsp_get_browser_img( $arg ) {
global $newstatpress_dir;
$lines = file( $newstatpress_dir . '/def/browser.dat' );
foreach ( $lines as $line_num => $browser ) {
list($name_browser,$id,$img_browser) = explode( '|', $browser );
if ( strcmp( $name_browser, $arg ) == 0 ) {
return $img_browser;
}
}
return '';
}
/**
* Check if the given ip is to ban
*
* @param string $arg the ip to check.
* @return '' id the address is banned.
*/
function nsp_check_ban_ip( $arg ) {
global $newstatpress_dir;
$lines = file( $newstatpress_dir . '/def/banips.dat' );
foreach ( $lines as $line_num => $banip ) {
if ( strpos( $arg, rtrim( $banip, "\n" ) ) === false ) {
continue;
}
return ''; // this is banned.
}
return $arg;
}
/**
* Get the search engines
*
* @param string $referrer the url to test.
* @return the search engine present in the url.
*/
function nsp_get_se( $referrer = null ) {
global $newstatpress_dir;
$key = null;
$lines = file( $newstatpress_dir . '/def/searchengines.dat' );
foreach ( $lines as $line_num => $se ) {
list($nome,$url,$key) = explode( '|', $se );
if ( strpos( $referrer, $url ) === false ) {
continue;
}
// find if.
$variables = nsp_get_query_pairs( html_entity_decode( $referrer ) );
null === $variables ? $i = 0 : $i = count( $variables );
while ( $i-- ) {
$tab = explode( '=', $variables[ $i ] );
if ( $tab[0] === $key ) {
return ( $nome . '|' . urldecode( $tab[1] ) );}
}
}
return null;
}
/**
* Get the spider from the given agent
*
* @param string $agent the agent string.
* @return agent the fount agent.
*************************************/
function nsp_get_spider( $agent = null ) {
global $newstatpress_dir;
$agent = str_replace( ' ', '', $agent );
$key = null;
$lines = file( $newstatpress_dir . '/def/spider.dat' );
foreach ( $lines as $line_num => $spider ) {
list($nome,$key) = explode( '|', $spider );
if ( strpos( $agent, $key ) === false ) {
continue;
}
// fount.
return $nome;
}
return null;
}
/**
* Get the previous month in 'YYYYMM' format
*
* @return the previous month.
*/
function nsp_lastmonth() {
$ta = getdate( current_time( 'timestamp' ) );
$year = $ta['year'];
$month = $ta['mon'];
--$month; // go back 1 month.
if ( 0 == $month ) : // if this month is Jan.
--$year; // go back a year.
$month = 12; // last month is Dec.
endif;
// return in format 'YYYYMM'.
return sprintf( $year . '%02d', $month );
}
/**
* Create or update the table
*
* @param string $action to do: update, create.
*************************************/
function nsp_build_plugin_sql_table( $action ) {
global $wpdb;
global $wp_db_version;
$table_name = NSP_TABLENAME;
$charset_collate = $wpdb->get_charset_collate();
$index_list = array(
array(
'Key_name' => 'spider_nation',
'Column_name' => '(spider, nation)',
),
array(
'Key_name' => 'ip_date',
'Column_name' => '(ip, date)',
),
array(
'Key_name' => 'agent',
'Column_name' => '(agent)',
),
array(
'Key_name' => 'search',
'Column_name' => '(search)',
),
array(
'Key_name' => 'referrer',
'Column_name' => '(referrer)',
),
array(
'Key_name' => 'feed_spider_os',
'Column_name' => '(feed, spider, os)',
),
array(
'Key_name' => 'os',
'Column_name' => '(os)',
),
array(
'Key_name' => 'date_feed_spider',
'Column_name' => '(date, feed, spider)',
),
array(
'Key_name' => 'feed_spider_browser',
'Column_name' => '(feed, spider, browser)',
),
array(
'Key_name' => 'browser',
'Column_name' => '(browser)',
),
);
// Add by chab
// IF the table is already created then DROP INDEX for update.
if ( '' === $action ) {
$action = 'create';
}
$sql_createtable = '
CREATE TABLE ' . $table_name . ' (
id mediumint(9) NOT NULL AUTO_INCREMENT,
date int(8),
time time,
ip varchar(39),
urlrequested varchar(250),
agent varchar(250),
referrer varchar(512),
search varchar(250),
nation varchar(2),
os varchar(30),
browser varchar(32),
searchengine varchar(16),
spider varchar(32),
feed varchar(8),
user varchar(16),
timestamp timestamp DEFAULT 0,
UNIQUE KEY id (id)';
if ( 'create' === $action ) {
foreach ( $index_list as $index ) {
$key_name = $index['Key_name'];
$column_name = $index['Column_name'];
$sql_createtable .= ", INDEX $key_name $column_name";
}
} elseif ( 'update' === $action ) {
foreach ( $index_list as $index ) {
$key_name = $index['Key_name'];
$column_name = $index['Column_name'];
// db call ok; no-cache ok. unprepared SQL OK.
// phpcs:ignore
if ( $wpdb->query(
// phpcs:ignore
$wpdb->prepare( "SHOW INDEXES FROM `$table_name` WHERE Key_name = %s", $key_name ) // phpcs:ignore
) === '' ) {
$sql_createtable .= ",\n INDEX $key_name $column_name";
}
}
}
$sql_createtable .= ") $charset_collate;";
if ( $wp_db_version >= 5540 ) {
$page = 'wp-admin/includes/upgrade.php';
} else {
$page = 'wp-admin/upgrade-functions.php';
}
require_once ABSPATH . $page;
dbDelta( $sql_createtable );
}
/**
* Get if this is a feed
*
* @param string $url the url to test.
* @return the kind of feed that is found.
*****************************************/
function nsp_is_feed( $url ) {
$tmp = get_bloginfo( 'rdf_url' );
if ( $tmp ) {
if ( stristr( $url, $tmp ) !== false ) {
return 'RDF'; }
}
$tmp = get_bloginfo( 'rss2_url' );
if ( $tmp ) {
if ( stristr( $url, $tmp ) !== false ) {
return 'RSS2'; }
}
$tmp = get_bloginfo( 'rss_url' );
if ( $tmp ) {
if ( stristr( $url, $tmp ) !== false ) {
return 'RSS'; }
}
$tmp = get_bloginfo( 'atom_url' );
if ( $tmp ) {
if ( stristr( $url, $tmp ) !== false ) {
return 'ATOM'; }
}
$tmp = get_bloginfo( 'comments_rss2_url' );
if ( $tmp ) {
if ( stristr( $url, $tmp ) !== false ) {
return 'COMMENT'; }
}
$tmp = get_bloginfo( 'comments_atom_url' );
if ( $tmp ) {
if ( stristr( $url, $tmp ) !== false ) {
return 'COMMENT'; }
}
if ( stristr( $url, 'wp-feed.php' ) !== false ) {
return 'RSS2'; }
if ( stristr( $url, '/feed/' ) !== false ) {
return 'RSS2'; }
return '';
}
/**
* Insert statistic into the database
************************************/
function nsp_stat_append() {
global $wpdb;
$table_name = NSP_TABLENAME;
global $userdata;
wp_get_current_user();
$feed = '';
// Time.
$timestamp = current_time( 'timestamp' );
$vdate = gmdate( 'Ymd', $timestamp );
$vtime = gmdate( 'H:i:s', $timestamp );
$timestamp = gmdate( 'Y-m-d H:i:s', $timestamp );
// IP.
if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
$ip_address = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ); // BASIC detection -> to delete if it works.
}
// Is this IP blacklisted from file?
if ( nsp_check_ban_ip( $ip_address ) === '' ) {
return ''; }
// Is this IP blacklisted from user?
$to_ignore = get_option( 'newstatpress_ignore_ip', array() );
foreach ( $to_ignore as $a_ip_range ) {
list ($ip_to_ignore, $mask) = @explode( '/', trim( $a_ip_range ) );
if ( empty( $mask ) ) {
$mask = 32;
}
$long_ip_to_ignore = ip2long( $ip_to_ignore );
$long_mask = bindec( str_pad( '', $mask, '1' ) . str_pad( '', 32 - $mask, '0' ) );
$long_masked_user_ip = ip2long( $ip_address ) & $long_mask;
$long_masked_ip_to_ignore = $long_ip_to_ignore & $long_mask;
if ( $long_masked_user_ip === $long_masked_ip_to_ignore ) {
return ''; }
}
if ( get_option( 'newstatpress_cryptip' ) === 'checked' ) {
$ip_address = crypt( $ip_address, NSP_TEXTDOMAIN );
}
// URL (requested).
$url_requested = nsp_url();
if ( preg_match( '/.ico$/i', $url_requested ) ) {
return ''; }
if ( preg_match( '/favicon.ico/i', $url_requested ) ) {
return ''; }
if ( preg_match( '/.css$/i', $url_requested ) ) {
return ''; }
if ( preg_match( '/.js$/i', $url_requested ) ) {
return ''; }
if ( stristr( $url_requested, content_url() ) !== false ) {
return ''; }
if ( stristr( $url_requested, admin_url() ) !== false ) {
return ''; }
$url_requested = esc_sql( $url_requested );
// Is a given permalink blacklisted?
$to_ignore = get_option( 'newstatpress_ignore_permalink', array() );
foreach ( $to_ignore as $a_filter ) {
if ( ! empty( $url_requested ) && strpos( $url_requested, $a_filter ) === 0 ) {
return ''; }
}
$referrer = ( isset( $_SERVER['HTTP_REFERER'] ) ? htmlentities( sanitize_text_field( wp_unslash( $_SERVER['HTTP_REFERER'] ) ) ) : '' );
$referrer = esc_url( $referrer );
$referrer = esc_sql( $referrer );
$user_agent = ( isset( $_SERVER['HTTP_USER_AGENT'] ) ? htmlentities( sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) ) : '' );
$user_agent = sanitize_text_field( $user_agent );
$user_agent = esc_sql( $user_agent );
$spider = nsp_get_spider( $user_agent );
if ( ( '' != $spider ) && ( get_option( 'newstatpress_donotcollectspider' ) === 'checked' ) ) {
return ''; }
// ininitalize to empty.
$searchengine = '';
$search_phrase = '';
if ( '' != $spider ) {
$os = '';
$browser = '';
} else {
// Trap feeds.
if ( isset( $_SERVER['REQUEST_URI'] ) ) {
$feed = nsp_is_feed( get_bloginfo( 'url' ) . sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
}
// Get OS and browser.
$os = nsp_get_os( $user_agent );
$browser = nsp_get_browser( $user_agent );
$exp_referrer = nsp_get_se( $referrer );
if ( isset( $exp_referrer ) ) {
list($searchengine,$search_phrase) = explode( '|', $exp_referrer );
}
}
// Country (ip2nation table) or language.
$countrylang = '';
if ( $wpdb->get_var( "SHOW TABLES LIKE 'ip2nation'" ) === 'ip2nation' ) {
$qry = $wpdb->get_row(
$wpdb->prepare(
'SELECT *
FROM ip2nation
WHERE ip < INET_ATON( %s )
ORDER BY ip DESC
LIMIT 0,1',
$ip_address
)
); // db call ok; no-cache ok.
if ( isset( $qry->country ) ) {
$countrylang = $qry->country;
}
}
if ( '' == $countrylang ) {
if ( isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) {
$countrylang = nsp_get_language( sanitize_text_field( wp_unslash( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) );
}
}
// Auto-delete visits if...
if ( get_option( 'newstatpress_autodelete' ) !== '' ) {
$int = filter_var( get_option( 'newstatpress_autodelete' ), FILTER_SANITIZE_NUMBER_INT );
// secure action.
if ( $int >= 1 ) {
$t = gmdate( 'Ymd', current_time( 'timestamp' ) - 86400 * $int * 30 );
// phpcs:ignore -- db call ok; no-cache ok.
$results = $wpdb->query(
$wpdb->prepare(
"DELETE FROM `$table_name`
WHERE date < %s
",
$t
)
); // phpcs:ignore: unprepared SQL OK.
}
}
// Auto-delete spiders visits if...
if ( get_option( 'newstatpress_autodelete_spiders' ) !== '' ) {
$int = filter_var( get_option( 'newstatpress_autodelete_spiders' ), FILTER_SANITIZE_NUMBER_INT );
// secure action.
if ( $int >= 1 ) {
$t = gmdate( 'Ymd', current_time( 'timestamp' ) - 86400 * $int * 30 );
// phpcs:ignore -- db call ok; no-cache ok.
$results = $wpdb->query(
$wpdb->prepare(
"DELETE FROM `$table_name`
WHERE date < %s and
feed='' and
spider<>''
",
$t
)
); // phpcs:ignore: unprepared SQL OK.
}
}
if ( ( ! is_user_logged_in() ) || ( get_option( 'newstatpress_collectloggeduser' ) === 'checked' ) ) {
if ( is_user_logged_in() && ( get_option( 'newstatpress_collectloggeduser' ) === 'checked' ) ) {
$current_user = wp_get_current_user();
// Is a given name to ignore?
$to_ignore = get_option( 'newstatpress_ignore_users', array() );
foreach ( $to_ignore as $a_filter ) {
if ( $current_user->user_login === $a_filter ) {
return ''; }
}
}
// phpcs:ignore -- db call ok; no-cache ok.
if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name ) ) !== $table_name ) {
nsp_build_plugin_sql_table( 'create' );
}
$login = $userdata ? $userdata->user_login : null;
$results = $wpdb->insert(
$table_name,
array(
'date' => $vdate,
'time' => $vtime,
'ip' => substr( $ip_address, 0, 39 ),
'urlrequested' => substr( $url_requested, 0, 250 ),
'agent' => substr( wp_strip_all_tags( $user_agent ), 0, 250 ),
'referrer' => substr( $referrer, 0, 512 ),
'search' => substr( wp_strip_all_tags( $search_phrase ), 0, 250 ),
'nation' => substr( $countrylang, 0, 2 ),
'os' => substr( $os, 0, 30 ),
'browser' => substr( $browser, 0, 32 ),
'searchengine' => substr( $searchengine, 0, 16 ),
'spider' => substr( $spider, 0, 32 ),
'feed' => substr( $feed, 0, 8 ),
'user' => substr( $login, 0, 16 ),
'timestamp' => $timestamp,
),
array( '%s' )
);
}
}
add_action( 'send_headers', 'nsp_stat_append' );
/**
* Generate the Ajax code for the given variable
*
* @param string $var variable to get.
* @param int $limit optional limit value for query.
* @param string $flag optional flag value for checked.
* @param string $url optional url address.
************************************************/
function nsp_generate_ajax_var( $var, $limit = 0, $flag = '', $url = '' ) {
global $newstatpress_dir;
global $_newstatpress;
wp_enqueue_script( 'wp_ajax_nsp_variables_' . $var, plugins_url( './includes/js/nsp_variables_' . $var . '.js', __FILE__ ), array( 'jquery' ), $_newstatpress['version'], true );
wp_localize_script(
'wp_ajax_nsp_variables_' . $var,
'nsp_variablesAjax_' . $var,
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'postCommentNonce' => wp_create_nonce( 'newstatpress-nsp_variables-nonce' ),
'VAR' => $var,
'URL' => $url,
'FLAG' => $flag,
'LIMIT' => $limit,
)
);
$res = '_';
return $res;
}
/**
* Return the expanded vars into the give code. API to use for users.
*
* @param string $body the body.
*/
function newstatpress_print( $body = '' ) {
return nsp_expand_vars_inside_code( $body );
}
/**
* Expand vars into the give code
*
* @param string $body the code where to look for variables to expand.
* @return the modified code.
************************************************************/
function nsp_expand_vars_inside_code( $body ) {
global $wpdb;
$table_name = NSP_TABLENAME;
$vars_list = array(
'visits',
'yvisits',
'mvisits',
'wvisits',
'totalvisits',
'totalpageviews',
'todaytotalpageviews',
'alltotalvisits',
'monthtotalpageviews',
);
// look for $vars_list.
foreach ( $vars_list as $var ) {
if ( strpos( strtolower( $body ), "%$var%" ) !== false ) {
$body = str_replace( "%$var%", nsp_generate_ajax_var( $var ), $body );
}
}
// look for %thistotalvisits%.
if ( strpos( strtolower( $body ), '%thistotalvisits%' ) !== false ) {
$body = str_replace( '%thistotalvisits%', nsp_generate_ajax_var( 'thistotalvisits', 0, '', nsp_url() ), $body );
}
// look for %since%.
if ( strpos( strtolower( $body ), '%since%' ) !== false ) {
// not needs prepare.
// phpcs:ignore -- db call ok; no-cache ok.
$qry = $wpdb->get_var(
"SELECT date
FROM `$table_name`
ORDER BY date
LIMIT 1
"
); // phpcs:ignore: unprepared SQL OK.
$body = str_replace( '%since%', nsp_hdate( $qry ), $body );
}
// look for %os%.
if ( strpos( strtolower( $body ), '%os%' ) !== false ) {
$user_agent = ( isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '' );
$os = nsp_get_os( $user_agent );
$body = str_replace( '%os%', $os, $body );
}
// look for %browser%.
if ( strpos( strtolower( $body ), '%browser%' ) !== false ) {
$browser = nsp_get_browser( $user_agent );
$body = str_replace( '%browser%', $browser, $body );
}
// look for %ip%.
if ( strpos( strtolower( $body ), '%ip%' ) !== false ) {
$ip_address = ( isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '' );
$body = str_replace( '%ip%', $ip_address, $body );
}
// look for %visitorsonline%.
if ( strpos( strtolower( $body ), '%visitorsonline%' ) !== false ) {
$act_time = current_time( 'timestamp' );
$from_time = gmdate( 'Y-m-d H:i:s', strtotime( '-4 minutes', $act_time ) );
$to_time = gmdate( 'Y-m-d H:i:s', $act_time );
// use prepare.
// phpcs:ignore -- db call ok; no-cache ok.
$qry = $wpdb->get_var(
$wpdb->prepare(
"SELECT count(DISTINCT(ip)) AS visitors
FROM `$table_name`
WHERE
spider='' AND
feed='' AND
date = %s AND
timestamp BETWEEN %s AND %s
",
gmdate( 'Ymd', $act_time ),
$from_time,
$to_time
)
); // phpcs:ignore: unprepared SQL OK.
$body = str_replace( '%visitorsonline%', $qry, $body );
}
// look for %usersonline%.
if ( strpos( strtolower( $body ), '%usersonline%' ) !== false ) {
$act_time = current_time( 'timestamp' );
$from_time = gmdate( 'Y-m-d H:i:s', strtotime( '-4 minutes', $act_time ) );
$to_time = gmdate( 'Y-m-d H:i:s', $act_time );
// use prepare.
// phpcs:ignore -- db call ok; no-cache ok.
$qry = $wpdb->get_var(
$wpdb->prepare(
"SELECT count(DISTINCT(ip)) AS users
FROM `$table_name`
WHERE
spider='' AND
feed='' AND
date = %s AND
user<>'' AND
timestamp BETWEEN %s AND %s
",
gmdate( 'Ymd', $act_time ),
$from_time,
$to_time
)
); // phpcs:ignore: unprepared SQL OK.
$body = str_replace( '%usersonline%', $qry, $body );
}
// look for %toppost%.
if ( strpos( strtolower( $body ), '%toppost%' ) !== false ) {
// not needs prepare.
// phpcs:ignore -- db call ok; no-cache ok.
$qry = $wpdb->get_row(
"SELECT urlrequested,count(*) AS totale
FROM `$table_name`
WHERE
spider='' AND
feed='' AND
urlrequested LIKE '%p=%'
GROUP BY urlrequested
ORDER BY totale DESC
LIMIT 1
"
); // phpcs:ignore: unprepared SQL OK.
$body = str_replace( '%toppost%', nsp_decode_url( $qry->urlrequested ), $body );
}
// look for %topbrowser%.
if ( strpos( strtolower( $body ), '%topbrowser%' ) !== false ) {
// not needs prepare.
// phpcs:ignore -- db call ok; no-cache ok.
$qry = $wpdb->get_row(
"SELECT browser,count(*) AS totale
FROM `$table_name`
WHERE
spider='' AND
feed=''
GROUP BY browser
ORDER BY totale DESC
LIMIT 1
"
); // phpcs:ignore: unprepared SQL OK.
$body = str_replace( '%topbrowser%', nsp_decode_url( $qry->browser ), $body );
}
// look for %topos%.
if ( strpos( strtolower( $body ), '%topos%' ) !== false ) {
// not needs prepare.
// phpcs:ignore -- db call ok; no-cache ok.
$qry = $wpdb->get_row(
"SELECT os,count(*) AS totale
FROM `$table_name`
WHERE
spider='' AND
feed=''
GROUP BY os
ORDER BY totale DESC
LIMIT 1
"
); // phpcs:ignore: unprepared SQL OK.
$body = str_replace( '%topos%', nsp_decode_url( $qry->os ), $body );
}
// look for %topsearch%.
if ( strpos( strtolower( $body ), '%topsearch%' ) !== false ) {
// not needs prepare.
// phpcs:ignore -- db call ok; no-cache ok.
$qry = $wpdb->get_row(
"SELECT search, count(*) AS csearch
FROM `$table_name`
WHERE
search<>''
GROUP BY search
ORDER BY csearch DESC
LIMIT 1
"
); // phpcs:ignore: unprepared SQL OK.
if ( is_object( $qry ) ) {
$body = str_replace( '%topsearch%', nsp_decode_url( $qry->search ), $body );
} else {
$body = str_replace( '%topsearch%', '', $body );
}
}
// look for %br%.
if ( strpos( strtolower( $body ), '%br%' ) !== false ) {
$body = str_replace( '%br%', '
', $body );
}
// look for %ul%.
if ( strpos( strtolower( $body ), '%ul%' ) !== false ) {
$body = str_replace( '%ul%', '', $body );
}
// look for %li%.
if ( strpos( strtolower( $body ), '%li%' ) !== false ) {
$body = str_replace( '%li%', '- ', $body );
}
// look for %/ul%.
if ( strpos( strtolower( $body ), '%/ul%' ) !== false ) {
$body = str_replace( '%/ul%', '
', $body );
}
// look for %/li%.
if ( strpos( strtolower( $body ), '%/li%' ) !== false ) {
$body = str_replace( '%/li%', '', $body );
}
return $body;
}
// TODO : if working, move the contents into the caller instead of this function.
/**
* Get top posts
*
* @param int $limit the number of post to show.
* @param string $showcounts if checked show totals.
* @return result of extraction
*******************************************/
function nsp_top_posts( $limit = 5, $showcounts = 'checked' ) {
return nsp_generate_ajax_var( 'widget_topposts', $limit, $showcounts );
}
/**
* Build NewsStatPress Widgets: Stat and TopPosts
*
* @param string $args arguments.
************************************************/
function nsp_widget_init( $args ) {
if ( ! function_exists( 'wp_register_sidebar_widget' ) || ! function_exists( 'wp_register_widget_control' ) ) {
return;
}
/**
* Statistics Widget control.
*/
function nsp_widget_stats_control() {
global $nsp_widget_vars;
$options = get_option( 'widget_newstatpress' );
if ( ! is_array( $options ) ) {
$options = array(
'title' => 'NewStatPress Stats',
'body' => 'Visits today: %visits%',
);
}
if ( isset( $_POST['newstatpress-submit'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['newstatpress-submit'] ) ), 'nsp_widget_stats_control' ) ) {
if ( isset( $_POST['newstatpress-title'] ) ) {
$options['title'] = sanitize_text_field( wp_unslash( $_POST['newstatpress-title'] ) );
}
if ( isset( $_POST['newstatpress-body'] ) ) {
$options['body'] = stripslashes( sanitize_text_field( wp_unslash( $_POST['newstatpress-body'] ) ) );
}
update_option( 'widget_newstatpress', $options );
}
$title = htmlspecialchars( $options['title'], ENT_QUOTES );
$body = htmlspecialchars( $options['body'], ENT_QUOTES );
// the form.
echo "
' . "
" . esc_html__( 'Stats available: ', 'newstatpress' ) . "
";
foreach ( $nsp_widget_vars as $var ) {
echo "%" . esc_html( $var[0] ) . '% ';
esc_html( $var[1] );
echo ' | ';
}
echo '
';
}
/**
* Widget stats
*
* @param string $args arguments.
*/
function nsp_widget_stats( $args ) {
$options = get_option( 'widget_newstatpress' );
$title = esc_js( $options['title'] );
$body = esc_js( $options['body'] );
echo wp_kses_post( $args['before_widget'] );
print( wp_kses_post( $args['before_title'] ) . esc_html( $title ) . wp_kses_post( $args['after_title'] ) );
print wp_kses_post( nsp_expand_vars_inside_code( $body ) );
echo wp_kses_post( $args['after_widget'] );
}
wp_register_sidebar_widget( 'NewStatPress', 'NewStatPress Stats', 'nsp_widget_stats' );
wp_register_widget_control( 'NewStatPress', array( 'NewStatPress', 'widgets' ), 'nsp_widget_stats_control', 300, 210 );
/**
* Top posts Widget control.
*/
function nsp_widget_top_posts_control() {
$options = get_option( 'widget_newstatpresstopposts' );
if ( ! is_array( $options ) ) {
$options = array(
'title' => 'NewStatPress TopPosts',
'howmany' => '5',
'showcounts' => 'checked',
);
}
if ( isset( $_POST['newstatpresstopposts-submit'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['newstatpresstopposts-submit'] ) ), 'nsp_widget_top_posts_control' ) ) {
if ( isset( $_POST['newstatpresstopposts-title'] ) ) {
$options['title'] = sanitize_text_field( wp_unslash( $_POST['newstatpresstopposts-title'] ) );
}
if ( isset( $_POST['newstatpresstopposts-howmany'] ) ) {
$options['howmany'] = filter_var( wp_unslash( $_POST['newstatpresstopposts-howmany'] ), FILTER_SANITIZE_NUMBER_INT );
}
if ( isset( $_POST['newstatpresstopposts-showcounts'] ) ) {
$options['showcounts'] = sanitize_text_field( wp_unslash( $_POST['newstatpresstopposts-showcounts'] ) );
}
if ( '1' === $options['showcounts'] ) {
$options['showcounts'] = 'checked';
}
update_option( 'widget_newstatpresstopposts', $options );
}
$title = htmlspecialchars( $options['title'], ENT_QUOTES );
$howmany = htmlspecialchars( $options['howmany'], ENT_QUOTES );
$showcounts = htmlspecialchars( $options['showcounts'], ENT_QUOTES );
// the form.
echo "
";
echo '';
echo '';
}
/**
* Widget top posts
*
* @param string $args args to use.
*/
function nsp_widget_top_posts( $args ) {
$options = get_option( 'widget_newstatpresstopposts' );
$title = htmlspecialchars( $options['title'], ENT_QUOTES );
$howmany = htmlspecialchars( $options['howmany'], ENT_QUOTES );
$showcounts = htmlspecialchars( $options['showcounts'], ENT_QUOTES );
echo wp_kses_post( $args['before_widget'] );
print( wp_kses_post( $args['before_title'] ) . esc_html( $title ) . wp_kses_post( $args['after_title'] ) );
print wp_kses_post( nsp_top_posts( $howmany, $showcounts ) );
echo wp_kses_post( $args['after_widget'] );
}
wp_register_sidebar_widget( 'NewStatPressTopPosts', 'NewStatPress TopPosts', 'nsp_widget_top_posts' );
wp_register_widget_control( 'NewStatPressTopPosts', array( 'NewStatPressTopPosts', 'widgets' ), 'nsp_widget_top_posts_control', 300, 110 );
}
add_action( 'plugins_loaded', 'nsp_widget_init' );
/**
* Calculate variations
*
* @param int $month month.
* @param int $lmonth lmonth.
*/
function nsp_calculate_variation( $month, $lmonth ) {
$target = round(
$month / (
( gmdate( 'd', current_time( 'timestamp' ) ) - 1 +
( gmdate( 'H', current_time( 'timestamp' ) ) +
( gmdate( 'i', current_time( 'timestamp' ) ) + 1 ) / 60.0 ) / 24.0 ) ) * gmdate( 't', current_time( 'timestamp' ) )
);
$monthchange = null;
$added = null;
if ( 0 <> $lmonth ) {
$percent_change = round( 100 * ( $month / $lmonth ) - 100, 1 );
$percent_target = round( 100 * ( $target / $lmonth ) - 100, 1 );
if ( $percent_change >= 0 ) {
$percent_change = sprintf( "+%'04.1f", $percent_change );
$monthchange = "($percent_change%) | ";
} else {
$percent_change = sprintf( "%'05.1f", $percent_change );
$monthchange = "($percent_change%) | ";
}
if ( $percent_target >= 0 ) {
$percent_target = sprintf( "+%'04.1f", $percent_target );
$added = "($percent_target%) | ";
} else {
$percent_target = sprintf( "%'05.1f", $percent_target );
$added = "($percent_target%) | ";
}
} else {
$monthchange = ' | ';
$added = " | ";
}
$calculated_result = array( $monthchange, $target, $added );
return $calculated_result;
}
register_activation_hook( __FILE__, 'nsp_build_plugin_sql_table' );
?>