PluginProbe
NewStatPress / 1.4.0
NewStatPress v1.4.0
1.4.5 1.4.3 1.4.4 0.8.8 0.8.9 0.9.0 0.9.1 0.9.2 0.9.3 0.9.4 0.9.5 0.9.6 0.9.7 0.9.8 0.9.9 1.0.0 1.0.1 1.0.2 1.0.3 1.0.4 1.0.5 1.0.6 1.0.7 1.0.8 1.0.9 All 136 releases
newstatpress / newstatpress.php

newstatpress.php in NewStatPress 1.4.0, at newstatpress.php

1,899 lines 60.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**********************************************************
3 * Plugin Name: NewStatPress
4 * Plugin URI: http://newstatpress.altervista.org
5 * Text Domain: newstatpress
6 * Description: Real time stats for your WordPress blog
7 * Version: 1.4.0
8 * Author: Stefano Tognon and cHab (from Daniele Lippi works)
9 * Author URI: http://newstatpress.altervista.org
10 *
11 * @package NewStatpress
12 ************************************************************/
13
14 // Make sure plugin remains secure if called directly.
15 if ( ! defined( 'ABSPATH' ) ) {
16 if ( ! headers_sent() ) {
17 header( 'HTTP/1.1 403 Forbidden' ); }
18 die( esc_html__( 'ERROR: This plugin requires WordPress and will not function if called directly.', 'newstatpress' ) );
19 }
20
21 $_newstatpress['version'] = '1.4.0';
22 $_newstatpress['feedtype'] = '';
23
24 global $newstatpress_dir,
25 $wpdb,
26 $nsp_option_vars,
27 $nsp_overview_screen,
28 $nsp_widget_vars;
29
30 define( 'NSP_TEXTDOMAIN', 'newstatpress' );
31 define( 'NSP_PLUGINNAME', 'NewStatPress' );
32 define( 'NSP_REQUIRED_WP_VERSION', '3.5' );
33 define( 'NSP_NOTICENEWS', true );
34 define( 'NSP_TABLENAME', $wpdb->prefix . 'statpress' );
35 define( 'NSP_BASENAME', dirname( plugin_basename( __FILE__ ) ) );
36 define( 'NSP_PLUGIN_BASENAME', plugin_basename( __FILE__ ) );
37 define( 'NSP_SERVER_NAME', nsp_get_server_name() );
38 define( 'NSP_RATING_URL', 'https://wordpress.org/support/view/plugin-reviews/' . NSP_TEXTDOMAIN );
39 define( 'NSP_PLUGIN_URL', 'http://newstatpress.altervista.org' );
40 define( 'NSP_DONATE_URL', 'https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=F5S5PF4QBWU7E' );
41 define( 'NSP_SUPPORT_URL', 'https://wordpress.org/support/plugin/' . NSP_TEXTDOMAIN );
42
43 // user compatibility way to get dir.
44 $newstatpress_dir = plugin_dir_path( __FILE__ );
45
46
47 $nsp_option_vars = array( // list of option variable name, with default value associated.
48 'overview' => array(
49 'name' => 'newstatpress_el_overview',
50 'value' => '10',
51 ),
52 'top_days' => array(
53 'name' => 'newstatpress_el_top_days',
54 'value' => '5',
55 ),
56 'os' => array(
57 'name' => 'newstatpress_el_os',
58 'value' => '10',
59 ),
60 'browser' => array(
61 'name' => 'newstatpress_el_browser',
62 'value' => '10',
63 ),
64 'feed' => array(
65 'name' => 'newstatpress_el_feed',
66 'value' => '5',
67 ),
68 'searchengine' => array(
69 'name' => 'newstatpress_el_searchengine',
70 'value' => '10',
71 ),
72 'search' => array(
73 'name' => 'newstatpress_el_search',
74 'value' => '20',
75 ),
76 'referrer' => array(
77 'name' => 'newstatpress_el_referrer',
78 'value' => '10',
79 ),
80 'languages' => array(
81 'name' => 'newstatpress_el_languages',
82 'value' => '20',
83 ),
84 'spiders' => array(
85 'name' => 'newstatpress_el_spiders',
86 'value' => '10',
87 ),
88 'pages' => array(
89 'name' => 'newstatpress_el_pages',
90 'value' => '5',
91 ),
92 'visitors' => array(
93 'name' => 'newstatpress_el_visitors',
94 'value' => '5',
95 ),
96 'daypages' => array(
97 'name' => 'newstatpress_el_daypages',
98 'value' => '5',
99 ),
100 'ippages' => array(
101 'name' => 'newstatpress_el_ippages',
102 'value' => '5',
103 ),
104 'ip_per_page_newspy' => array(
105 'name' => 'newstatpress_ip_per_page_newspy',
106 'value' => '',
107 ),
108 'visits_per_ip_newspy' => array(
109 'name' => 'newstatpress_visits_per_ip_newspy',
110 'value' => '',
111 ),
112 'bot_per_page_spybot' => array(
113 'name' => 'newstatpress_bot_per_page_spybot',
114 'value' => '',
115 ),
116 'visits_per_bot_spybot' => array(
117 'name' => 'newstatpress_visits_per_bot_spybot',
118 'value' => '',
119 ),
120 'autodelete' => array(
121 'name' => 'newstatpress_autodelete',
122 'value' => '',
123 ),
124 'autodelete_spiders' => array(
125 'name' => 'newstatpress_autodelete_spiders',
126 'value' => '',
127 ),
128 'daysinoverviewgraph' => array(
129 'name' => 'newstatpress_daysinoverviewgraph',
130 'value' => '',
131 ),
132 'ignore_users' => array(
133 'name' => 'newstatpress_ignore_users',
134 'value' => '',
135 ),
136 'ignore_ip' => array(
137 'name' => 'newstatpress_ignore_ip',
138 'value' => '',
139 ),
140 'ignore_permalink' => array(
141 'name' => 'newstatpress_ignore_permalink',
142 'value' => '',
143 ),
144 'updateint' => array(
145 'name' => 'newstatpress_updateint',
146 'value' => '',
147 ),
148 'calculation' => array(
149 'name' => 'newstatpress_calculation_method',
150 'value' => 'classic',
151 ),
152 'menu_cap' => array(
153 'name' => 'newstatpress_mincap',
154 'value' => 'read',
155 ),
156 'menuoverview_cap' => array(
157 'name' => 'newstatpress_menuoverview_cap',
158 'value' => 'switch_themes',
159 ),
160 'menudetails_cap' => array(
161 'name' => 'newstatpress_menudetails_cap',
162 'value' => 'switch_themes',
163 ),
164 'menuvisits_cap' => array(
165 'name' => 'newstatpress_menuvisits_cap',
166 'value' => 'switch_themes',
167 ),
168 'menusearch_cap' => array(
169 'name' => 'newstatpress_menusearch_cap',
170 'value' => 'switch_themes',
171 ),
172 'menuoptions_cap' => array(
173 'name' => 'newstatpress_menuoptions_cap',
174 'value' => 'edit_users',
175 ),
176 'menutools_cap' => array(
177 'name' => 'newstatpress_menutools_cap',
178 'value' => 'switch_themes',
179 ),
180 'menucredits_cap' => array(
181 'name' => 'newstatpress_menucredits_cap',
182 'value' => 'read',
183 ),
184 'apikey' => array(
185 'name' => 'newstatpress_apikey',
186 'value' => 'read',
187 ),
188 'ip2nation' => array(
189 'name' => 'newstatpress_ip2nation',
190 'value' => 'none',
191 ),
192 'mail_notification' => array(
193 'name' => 'newstatpress_mail_notification',
194 'value' => 'disabled',
195 ),
196 'mail_notification_freq' => array(
197 'name' => 'newstatpress_mail_notification_freq',
198 'value' => 'daily',
199 ),
200 'mail_notification_address' => array(
201 'name' => 'newstatpress_mail_notification_emailaddress',
202 'value' => '',
203 ),
204 'mail_notification_time' => array(
205 'name' => 'newstatpress_mail_notification_time',
206 'value' => '',
207 ),
208 'mail_notification_info' => array(
209 'name' => 'newstatpress_mail_notification_info',
210 'value' => '',
211 ),
212 'mail_notification_sender' => array(
213 'name' => 'newstatpress_mail_notification_sender',
214 'value' => 'NewsStatPress',
215 ),
216 'settings' => array(
217 'name' => 'newstatpress_settings',
218 'value' => '',
219 ),
220 'stats_offsets' => array(
221 'name' => 'newstatpress_stats_offsets',
222 'value' => '0',
223 ),
224 );
225
226 $nsp_widget_vars = array( // list of widget variables name, with description associated.
227 array( 'visits', __( 'Today visits', 'newstatpress' ) ),
228 array( 'yvisits', __( 'Yesterday visits', 'newstatpress' ) ),
229 array( 'mvisits', __( 'Month visits', 'newstatpress' ) ),
230 array( 'wvisits', __( 'Week visits', 'newstatpress' ) ),
231 array( 'totalvisits', __( 'Total visits', 'newstatpress' ) ),
232 array( 'totalpageviews', __( 'Total pages view', 'newstatpress' ) ),
233 array( 'todaytotalpageviews', __( 'Total pages view today', 'newstatpress' ) ),
234 array( 'thistotalvisits', __( 'This page, total visits', 'newstatpress' ) ),
235 array( 'alltotalvisits', __( 'All page, total visits', 'newstatpress' ) ),
236 array( 'os', __( 'Visitor Operative System', 'newstatpress' ) ),
237 array( 'browser', __( 'Visitor Browser', 'newstatpress' ) ),
238 array( 'ip', __( 'Visitor IP address', 'newstatpress' ) ),
239 array( 'since', __( 'Date of the first hit', 'newstatpress' ) ),
240 array( 'visitorsonline', __( 'Counts all online visitors', 'newstatpress' ) ),
241 array( 'usersonline', __( 'Counts logged online visitors', 'newstatpress' ) ),
242 array( 'monthtotalpageviews', __( 'Total page view in the month', 'newstatpress' ) ),
243 array( 'toppost', __( 'The most viewed Post', 'newstatpress' ) ),
244 );
245
246 /**
247 * Check to update of the plugin
248 * Added by cHab
249 *******************************/
250 function nsp_update_check() {
251
252 global $_newstatpress;
253 $active_version = get_option( 'newstatpress_version', '0' );
254 $admin_notices = get_option( 'newstatpress_admin_notices' );
255
256 if ( ! empty( $admin_notices ) ) {
257 add_action( 'admin_notices', 'nsp_admin_notices' );
258 }
259
260 // check version, update installation date and update notice status.
261 if ( version_compare( $active_version, $_newstatpress['version'], '<' ) ) {
262 if ( version_compare( $active_version, '1.1.0', '<' ) ) {
263 nsp_activation( 'old' ); // for old installation > 14 days since nsp 1.1.4.
264 }
265 if ( NSP_NOTICENEWS ) {
266 global $current_user;
267 $status = get_user_meta( $current_user->ID, 'newstatpress_nag_status', true );
268 $status['news'] = false;
269 update_user_meta( $current_user->ID, 'newstatpress_nag_status', $status );
270 }
271 update_option( 'newstatpress_version', $_newstatpress['version'] );
272 }
273
274 // check if is compatible with WP Version.
275 global $wp_version;
276 if ( version_compare( $wp_version, NSP_REQUIRED_WP_VERSION, '<' ) ) {
277 deactivate_plugins( NSP_PLUGIN_BASENAME );
278 // translators: placeholder for versions.
279 $notice_text = sprintf( __( 'Plugin %1$s deactivated. WordPress Version %2$s required. Please upgrade WordPress to the latest version.', 'newstatpress' ), NSP_PLUGINNAME, NSP_REQUIRED_WP_VERSION );
280 $new_admin_notice = array(
281 'style' => 'error',
282 'notice' => $notice_text,
283 );
284 update_option( 'newstatpress_admin_notices', $new_admin_notice );
285 add_action( 'admin_notices', 'nsp_admin_notices' );
286 return false;
287 }
288
289 nsp_check_nag_notices();
290
291 }
292 add_action( 'admin_init', 'nsp_update_check' );
293
294 /**
295 * Check and Export if capability of user allow that
296 * need here due to header change
297 * Updated by cHab
298 ***************************************************/
299 function nsp_check_export() {
300 global $nsp_option_vars;
301 global $current_user;
302 wp_get_current_user();
303
304 // phpcs:ignore -- nonce is verified inside nsp_export_now, so warning can be suppressed.
305 if ( isset( $_GET['newstatpress_action'] ) && 'exportnow' === $_GET['newstatpress_action'] ) {
306 $tools_capability = get_option( 'newstatpress_menutools_cap' );
307 if ( ! $tools_capability ) { // default value.
308 $tools_capability = $nsp_option_vars['menutools_cap']['value'];
309 }
310 if ( user_can( $current_user, $tools_capability ) ) {
311 require 'includes/nsp-tools.php';
312 nsp_export_now();
313 }
314 }
315 }
316 add_action( 'init', 'nsp_check_export' );
317
318 /**
319 * Installation time update of the plugin
320 * Added by cHab
321 */
322 register_activation_hook( __FILE__, 'nsp_activation' );
323
324 /**
325 * Activate plugin
326 *
327 * @param string $arg eventual argument.
328 */
329 function nsp_activation( $arg = '' ) {
330 global $nsp_option_vars;
331 $nsp_settings = get_option( $nsp_option_vars['settings']['name'] );
332 if ( empty( $nsp_settings['install_time'] ) ) {
333 $nsp_settings['install_time'] = time();
334 if ( 'old' === $arg ) {
335 $nsp_settings['install_time'] = time() - 7776000;
336 }
337 update_option( 'newstatpress_settings', $nsp_settings );
338 }
339 }
340
341 /**
342 * Load CSS style, languages files, extra files
343 * Added by cHab
344 ***********************************************/
345 function nsp_register_plugin_styles_and_scripts() {
346 global $_newstatpress;
347
348 // CSS.
349 $style_path = plugins_url( './css/style.css', __FILE__ );
350
351 wp_register_style( 'NewStatPressStyles', $style_path, array(), $_newstatpress['version'] );
352 wp_enqueue_style( 'NewStatPressStyles' );
353
354 wp_enqueue_script( 'jquery-ui-core' );// enqueue jQuery UI Core.
355 wp_enqueue_script( 'jquery-ui-tabs' );// enqueue jQuery UI Tabs.
356
357 $style_path2 = plugins_url( './css/pikaday.css', __FILE__ );
358
359 wp_register_style( 'pikaday', $style_path2, array(), $_newstatpress['version'] );
360 wp_enqueue_style( 'pikaday' );
361
362 wp_enqueue_style( 'NewStatPressStyles', get_stylesheet_uri(), array( 'dashicons' ), '1.0' );
363
364 // Load the postbox script that provides the widget style boxes.
365 wp_enqueue_script( 'common' );
366 wp_enqueue_script( 'wp-lists' );
367 wp_enqueue_script( 'postbox' ); // meta box.
368
369 // JS and jQuery.
370 $scripts = array(
371 'moment' => plugins_url( './js/moment.min.js', __FILE__ ),
372 'pikaday' => plugins_url( './js/pikaday.js', __FILE__ ),
373 'NewStatPressJs' => plugins_url( './js/nsp_general.js', __FILE__ ),
374 );
375 foreach ( $scripts as $key => $sc ) {
376 wp_register_script( $key, $sc, array(), $_newstatpress['version'], true );
377
378 if ( 'NewStatPressJs' === $key ) {
379 wp_localize_script(
380 'NewStatPressJs',
381 'ExtData',
382 array(
383 'Credit' => plugins_url( './includes/json/credit.json', __FILE__ ),
384 'Lang' => plugins_url( './includes/json/lang.json', __FILE__ ),
385 'Resources' => plugins_url( './includes/json/ressources.json', __FILE__ ),
386 'Donation' => plugins_url( './includes/json/donation.json', __FILE__ ),
387 'Domain' => plugins_url( './images/domain', __FILE__ ),
388 )
389 );
390 }
391
392 wp_enqueue_script( $key );
393 }
394
395 }
396 add_action( 'admin_enqueue_scripts', 'nsp_register_plugin_styles_and_scripts' );
397
398 /**
399 * Load text domain
400 */
401 function nsp_load_textdomain() {
402 load_plugin_textdomain( 'newstatpress', false, NSP_BASENAME . '/langs' );
403 }
404 add_action( 'plugins_loaded', 'nsp_load_textdomain' );
405
406 if ( is_admin() ) { // load dashboard and extra functions.
407 require 'includes/nsp-functions-extra.php';
408 require 'includes/nsp-dashboard.php';
409
410 add_action( 'wp_dashboard_setup', 'nsp_add_dashboard_widget' );
411 }
412 require 'includes/api/variables.php';
413 require 'includes/api/external.php';
414 require 'includes/nsp-core.php';
415
416 // register actions for ajax variables API.
417 add_action( 'wp_ajax_nsp_variables', 'nsp_variables_ajax' );
418 add_action( 'wp_ajax_nopriv_nsp_variables', 'nsp_variables_ajax' ); // need this to serve non logged in users.
419
420 // register actions for ajax external API.
421 add_action( 'wp_ajax_nsp_external', 'nsp_external_api_ajax_n' );
422 add_action( 'wp_ajax_nopriv_nsp_external', 'nsp_external_api_ajax' ); // need this to serve non logged in users.
423
424
425 /*************************************
426 * Add pages for NewStatPress plugin *
427 *************************************/
428 function nsp_build_plugin_menu() {
429
430 global $nsp_option_vars;
431 global $current_user;
432 global $nsp_overview_screen;
433 wp_get_current_user();
434
435 // Fix capability if it's not defined.
436 $capability = $nsp_option_vars['menu_cap']['value'];
437
438 $overview_capability = get_option( 'newstatpress_menuoverview_cap' );
439 if ( ! $overview_capability ) { // default value.
440 $overview_capability = $nsp_option_vars['menuoverview_cap']['value'];
441 }
442
443 $details_capability = get_option( 'newstatpress_menudetails_cap' );
444 if ( ! $details_capability ) { // default value.
445 $details_capability = $nsp_option_vars['menudetails_cap']['value'];
446 }
447
448 $visits_capability = get_option( 'newstatpress_menuvisits_cap' );
449 if ( ! $visits_capability ) { // default value.
450 $visits_capability = $nsp_option_vars['menuvisits_cap']['value'];
451 }
452
453 $search_capability = get_option( 'newstatpress_menusearch_cap' );
454 if ( ! $search_capability ) { // default value.
455 $search_capability = $nsp_option_vars['menusearch_cap']['value'];
456 }
457
458 $tools_capability = get_option( 'newstatpress_menutools_cap' );
459 if ( ! $tools_capability ) { // default value.
460 $tools_capability = $nsp_option_vars['menutools_cap']['value'];
461 }
462
463 $options_capability = get_option( 'newstatpress_menuoptions_cap' );
464 if ( ! $options_capability ) { // default value.
465 $options_capability = $nsp_option_vars['menuoptions_cap']['value'];
466 }
467
468 $credits_capability = $nsp_option_vars['menucredits_cap']['value'];
469
470 // Display menu with personalized capabilities if user IS NOT "subscriber".
471 if ( user_can( $current_user, 'edit_posts' ) ) {
472 add_menu_page( 'NewStatPres', 'NewStatPress', $capability, 'nsp-main', 'nsp_newstatpress_main_c', plugins_url( 'newstatpress/images/stat.png', NSP_BASENAME ) );
473 $nsp_overview_screen = add_submenu_page( 'nsp-main', __( 'Overview', 'newstatpress' ), __( 'Overview', 'newstatpress' ), $overview_capability, 'nsp-main', 'nsp_newstatpress_main_c' );
474 add_submenu_page( 'nsp-main', __( 'Details', 'newstatpress' ), __( 'Details', 'newstatpress' ), $details_capability, 'nsp-details', 'nsp_display_details_c' );
475 add_submenu_page( 'nsp-main', __( 'Visits', 'newstatpress' ), __( 'Visits', 'newstatpress' ), $visits_capability, 'nsp-visits', 'nsp_display_visits_page_c' );
476 add_submenu_page( 'nsp-main', __( 'Search', 'newstatpress' ), __( 'Search', 'newstatpress' ), $search_capability, 'nsp-search', 'nsp_database_search_c' );
477 add_submenu_page( 'nsp-main', __( 'Tools', 'newstatpress' ), __( 'Tools', 'newstatpress' ), $tools_capability, 'nsp-tools', 'nsp_display_tools_page_c' );
478 add_submenu_page( 'nsp-main', __( 'Options', 'newstatpress' ), __( 'Options', 'newstatpress' ), $options_capability, 'nsp-options', 'nsp_options_c' );
479 add_submenu_page( 'nsp-main', __( 'Credits', 'newstatpress' ), __( 'Credits', 'newstatpress' ), $credits_capability, 'nsp-credits', 'nsp_display_credits_page_c' );
480
481 // Add action to load the meta boxes to the overview page.
482 add_action( 'load-' . $nsp_overview_screen, 'nsp_statistics_load_overview_page' );
483 add_action( 'admin_footer-' . $nsp_overview_screen, 'wptuts_print_script_in_footer' );
484 }
485 }
486 add_action( 'admin_menu', 'nsp_build_plugin_menu' );
487
488 /**
489 * Prints script in footer to 'initialises' the meta boxes
490 */
491 function wptuts_print_script_in_footer() {
492 ?>
493 <script>jQuery(document).ready(function(){ postboxes.add_postbox_toggles(pagenow);jQuery('.postbox h3').prepend('<a class="togbox">+</a> '); });</script>
494 <?php
495 }
496
497
498 /**
499 * Load overview page
500 */
501 function nsp_statistics_load_overview_page() {
502 global $nsp_overview_screen;
503 add_meta_box( 'nsp_lasthits_postbox', __( 'Last hits', 'newstatpress' ), 'nsp_generate_overview_lasthits', $nsp_overview_screen, 'normal', null, array( 'widget' => 'lasthits' ) );
504 add_meta_box( 'nsp_lastsearchterms_postbox', __( 'Last search terms', 'newstatpress' ), 'nsp_generate_overview_lastsearchterms', $nsp_overview_screen, 'normal', null, array( 'widget' => 'lastsearchterms' ) );
505 add_meta_box( 'nsp_lastreferrers_postbox', __( 'Last referrers', 'newstatpress' ), 'nsp_generate_overview_lastreferrers', $nsp_overview_screen, 'normal', null, array( 'widget' => 'lastreferrers' ) );
506 add_meta_box( 'nsp_agents_postbox', __( 'Last agents', 'newstatpress' ), 'nsp_generate_overview_agents', $nsp_overview_screen, 'normal', null, array( 'widget' => 'agents' ) );
507 add_meta_box( 'nsp_pages_postbox', __( 'Last pages', 'newstatpress' ), 'nsp_generate_overview_pages', $nsp_overview_screen, 'normal', null, array( 'widget' => 'pages' ) );
508 add_meta_box( 'nsp_spiders_postbox', __( 'Last spiders', 'newstatpress' ), 'nsp_generate_overview_spiders', $nsp_overview_screen, 'normal', null, array( 'widget' => 'spiders' ) );
509 }
510
511 /**
512 * Newstatpress main
513 */
514 function nsp_newstatpress_main_c() {
515 require 'includes/nsp-overview.php';
516 nsp_new_stat_press_main();
517 }
518
519 /**
520 * Display details
521 */
522 function nsp_display_details_c() {
523 require 'includes/nsp-details.php';
524 nsp_display_details();
525 }
526
527 /**
528 * Display credits page
529 */
530 function nsp_display_credits_page_c() {
531 require 'includes/nsp-credits.php';
532 nsp_display_credits_page();
533 }
534
535 /**
536 * Options
537 */
538 function nsp_options_c() {
539 require 'includes/nsp-options.php';
540 nsp_options();
541 }
542
543 /**
544 * Display tool page
545 */
546 function nsp_display_tools_page_c() {
547 require 'includes/nsp-tools.php';
548 nsp_display_tools_page();
549 }
550
551 /**
552 * Display visits page
553 */
554 function nsp_display_visits_page_c() {
555 require 'includes/nsp-visits.php';
556 nsp_display_visits_page();
557 }
558
559 /**
560 * Database search
561 */
562 function nsp_database_search_c() {
563 require 'includes/nsp-search.php';
564 nsp_database_search();
565 }
566
567
568 /**
569 * Get the url of the plugin
570 *
571 * @return the url of the plugin.
572 ********************************/
573 function nsp_plugin_url() {
574 // use only modern way to get it.
575 return plugin_dir_url( __FILE__ );
576 }
577
578 /**
579 * Get server name
580 *
581 * @return the server name.
582 */
583 function nsp_get_server_name() {
584 $server_name = '';
585 if ( ! empty( $_SERVER['HTTP_HOST'] ) ) {
586 $server_name = sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) );
587 } elseif ( ! empty( $_newstatpress_env['HTTP_HOST'] ) ) {
588 $server_name = $_newstatpress_env['HTTP_HOST'];
589 } elseif ( ! empty( $_SERVER['SERVER_NAME'] ) ) {
590 $server_name = sanitize_text_field( wp_unslash( $_SERVER['SERVER_NAME'] ) );
591 } elseif ( ! empty( $_newstatpress_env['SERVER_NAME'] ) ) {
592 $server_name = $_newstatpress_env['SERVER_NAME']; }
593 return esc_html( nsp_case_trans( 'lower', $server_name ) );
594 }
595
596 /** TODO rsfb_strlen
597 * Convert case using multibyte version if available, if not, use defaults
598 *
599 * @param string $type type tp apply.
600 * @param string $string string to modify.
601 * @return modified string.
602 ***/
603 function nsp_case_trans( $type, $string ) {
604
605 switch ( $type ) {
606 case 'upper':
607 return function_exists( 'mb_strtoupper' ) ? mb_strtoupper( $string, 'UTF-8' ) : strtoupper( $string );
608 case 'lower':
609 return function_exists( 'mb_strtolower' ) ? mb_strtolower( $string, 'UTF-8' ) : strtolower( $string );
610 case 'ucfirst':
611 if ( function_exists( 'mb_strtoupper' ) && function_exists( 'mb_substr' ) ) {
612 $strtmp = mb_strtoupper( mb_substr( $string, 0, 1, 'UTF-8' ), 'UTF-8' ) . mb_substr( $string, 1, null, 'UTF-8' );
613 /* Added workaround for strange PHP bug in mb_substr() on some servers */
614 return rsfb_strlen( $string ) === rsfb_strlen( $strtmp ) ? $strtmp : ucfirst( $string );
615 } else {
616 return ucfirst( $string );
617 }
618 case 'ucwords':
619 return function_exists( 'mb_convert_case' ) ? mb_convert_case( $string, MB_CASE_TITLE, 'UTF-8' ) : ucwords( $string );
620 /***
621 * Note differences in results between ucwords() and this.
622 * ucwords() will capitalize first characters without altering other characters, whereas this will lowercase everything, but capitalize the first character of each word.
623 * This works better for our purposes, but be aware of differences.
624 */
625 default:
626 return $string;
627 }
628 }
629
630
631 /**
632 * Calculate offset_time in second to add to epoch format
633 * added by cHab
634 *
635 * @param int $t from time.
636 * @param int $tu to time.
637 * @return int $offset_time.
638 ***********************************************************/
639 function nsp_calculation_offset_time( $t, $tu ) {
640
641 list($current_hour, $current_minute) = explode( ':', gmdate( 'H:i', $t ) );
642 list($publishing_hour, $publishing_minutes) = explode( ':', $tu );
643
644 if ( $current_hour > $publishing_hour ) {
645 $plus_hour = 24 - $current_hour + $publishing_hour;
646 } else {
647 $plus_hour = $publishing_hour - $current_hour;
648 }
649
650 if ( $current_minute > $publishing_minutes ) {
651 $plus_minute = 60 - $current_minute + $publishing_minutes;
652 if ( 0 == $plus_hour ) {
653 $plus_hour = 23;
654 } else {
655 --$plus_hour;
656 }
657 } else {
658 $plus_minute = $publishing_minutes - $current_minute;
659 }
660
661 $offset_time = $plus_hour * 60 * 60 + $plus_minute * 60;
662 return $offset_time;
663 }
664
665 /**
666 * Parameters for newstatpress email notification
667 * added by cHab
668 *
669 * @param string $content_type not used.
670 * @retrun string the type of content.
671 ***************************************************/
672 function nsp_set_mail_content_type( $content_type ) {
673 return 'text/html';
674 }
675
676 /**
677 * Send an email notification with the overview statistics
678 * added by cHab
679 *
680 * @param string $arg type of mail ('' or 'test').
681 * @return string $email_confirmation.
682 *************************************/
683 function nsp_stat_by_email( $arg = '' ) {
684 global $nsp_option_vars, $support_pluginpage, $author_linkpage;
685 $date = gmdate( 'm/d/Y h:i:s a', time() );
686
687 add_filter( 'wp_mail_content_type', 'nsp_set_mail_content_type' );
688
689 $name = $nsp_option_vars['mail_notification']['name'];
690 $status = get_option( $name );
691 $name = $nsp_option_vars['mail_notification_freq']['name'];
692 $freq = get_option( $name );
693
694 $userna = esc_html( get_option( 'newstatpress_mail_notification_info' ) );
695
696 $blog_title = esc_html( get_bloginfo( 'name' ) );
697 // translators: placeholder for title.
698 $subject = sprintf( __( '[%s] Visits statistics', 'newstatpress' ), $blog_title );
699 if ( 'test' === $arg ) {
700 // translators: placeholder for title.
701 $subject = sprintf( __( '[%s] Visits statistics : test of email address', 'newstatpress' ), $blog_title );
702 }
703
704 require_once 'includes/api/nsp-api-dashboard.php';
705 $result_h = nsp_api_dashboard( 'HTML' );
706
707 $name = $nsp_option_vars['mail_notification_address']['name'];
708 $email_address = sanitize_email( get_option( $name ) );
709
710 $name = $nsp_option_vars['mail_notification_sender']['name'];
711 $sender = esc_html( get_option( $name ) );
712
713 if ( '' === $sender ) {
714 $sender = esc_html( $nsp_option_vars['mail_notification_sender']['value'] );
715 }
716
717 $support_pluginpage = "<a href='" . NSP_SUPPORT_URL . "' target='_blank'>" . __( 'support page', 'newstatpress' ) . '</a>';
718 $author_linkpage = "<a href='" . NSP_PLUGIN_URL . "/?page_id=2' target='_blank'>" . __( 'the author', 'newstatpress' ) . '</a>';
719
720 $credits_introduction = __( 'If you have found this plugin useful and you like it, thank you to take a moment to rate it.', 'newstatpress' );
721 // translators: placeholders for link.
722 $credits_introduction .= ' ' . sprintf( __( 'You can help to the plugin development by reporting bugs on the %1$s or by adding/updating translation by contacting directly %2$s.', 'newstatpress' ), $support_pluginpage, $author_linkpage );
723 $credits_introduction .= '<br />';
724 $credits_introduction .= __( 'NewStatPress is provided for free and is maintained only on free time, you can also consider a donation to support further work, directly on the plugin website or through the plugin (Credits Page).', 'newstatpress' );
725
726 $warning = __( 'This option is yet experimental, please report bugs or improvement (see link on the bottom)', 'newstatpress' );
727 $advising = __( 'You receive this email because you have enabled the statistics notification in the NewStatpress plugin (option menu) from your WP website ', 'newstatpress' );
728 $message = __( 'Dear', 'newstatpress' ) . " $userna, <br /> <br />
729 <i>$advising<STRONG>$blog_title</STRONG>.</i>
730 <mark>$warning.</mark> <br />
731 <br />" .
732 __( 'Statistics at', 'newstatpress' ) . " $date (" . __( 'server time', 'newstatpress' ) . ") from $blog_title: <br />
733 $result_h <br /> <br />"
734 . __( 'Best Regards from', 'newstatpress' ) . " <i>NewStatPress Team</i>. <br />
735 <br />
736 <br />
737 -- <br />
738 $credits_introduction";
739 $headers = 'From: ' . $sender . " <newstatpress@altervista.org> \r\n";
740 $email_confirmation = wp_mail( $email_address, $subject, $message, $headers );
741
742 remove_filter( 'wp_mail_content_type', 'nsp_set_mail_content_type' );
743
744 return $email_confirmation;
745 }
746
747 /**
748 * Mail notificatiom deactivate
749 */
750 function nsp_mail_notification_deactivate() {
751 wp_clear_scheduled_hook( 'nsp_mail_notification' );
752 }
753
754 // Hook mail publi.
755 add_action( 'nsp_mail_notification', 'nsp_stat_by_email' );
756
757
758
759
760 /**
761 * Add Settings link to plugins page
762 * added by cHab
763 *
764 * @param string $links the links.
765 * @param string $file the file.
766 * @return the link.
767 */
768 function nsp_add_settings_link( $links, $file ) {
769 if ( plugin_basename( __FILE__ ) !== $file ) {
770 return $links;
771 }
772
773 $settings_link = '<a href="admin.php?page=nsp_options">' . __( 'Settings', 'newstatpress' ) . '</a>';
774
775 array_unshift( $links, $settings_link );
776
777 return $links;
778 }
779 add_filter( 'plugin_action_links', 'nsp_add_settings_link', 10, 2 );
780
781
782
783 /**TODO useful or not????
784 * PHP 4 compatible mb_substr function
785 * (taken in statpress-visitors)
786 *
787 * @param string $str the string.
788 * @param int $x x value.
789 * @param int $y y value.
790 * @return the substring.
791 */
792 function nsp_my_substr( $str, $x, $y = 0 ) {
793 if ( 0 == $y ) {
794 $y = strlen( $str ) - $x;
795 }
796
797 if ( function_exists( 'mb_substr' ) ) {
798 return mb_substr( $str, $x, $y );
799 } else {
800 return substr( $str, $x, $y );
801 }
802 }
803
804
805 /**
806 * Decode the given url
807 *
808 * @param string $out_url the given url to decode.
809 * @return the decoded url.
810 ****************************************/
811 function nsp_decode_url( $out_url ) {
812 $out_url = filter_var( $out_url, FILTER_SANITIZE_URL );
813
814 if ( '' === $out_url ) {
815 $out_url = __( 'Page', 'newstatpress' ) . ': Home'; }
816 if ( substr( $out_url, 0, 4 ) === 'cat=' ) {
817 $out_url = __( 'Category', 'newstatpress' ) . ': ' . get_cat_name( substr( $out_url, 4 ) ); }
818 if ( substr( $out_url, 0, 2 ) === 'm=' ) {
819 $out_url = __( 'Calendar', 'newstatpress' ) . ': ' . substr( $out_url, 6, 2 ) . '/' . substr( $out_url, 2, 4 ); }
820 if ( substr( $out_url, 0, 2 ) === 's=' ) {
821 $out_url = __( 'Search', 'newstatpress' ) . ': ' . substr( $out_url, 2 ); }
822 if ( substr( $out_url, 0, 2 ) === 'p=' ) {
823 $sub_out = substr( $out_url, 2 );
824 $post_id_7 = get_post( $sub_out, ARRAY_A );
825 $out_url = $post_id_7['post_title'];
826 }
827 if ( substr( $out_url, 0, 8 ) === 'page_id=' ) {
828 $sub_out = substr( $out_url, 8 );
829 $post_id_7 = get_page( $sub_out, ARRAY_A );
830 $out_url = __( 'Page', 'newstatpress' ) . ': ' . $post_id_7['post_title'];
831 }
832 return $out_url;
833 }
834
835
836 /**
837 * Get url
838 *
839 * @retrun the url.
840 */
841 function nsp_url() {
842 $url_requested = ( isset( $_SERVER['QUERY_STRING'] ) ? filter_var( wp_unslash( $_SERVER['QUERY_STRING'] ), FILTER_SANITIZE_URL ) : '' );
843 if ( '' === $url_requested ) { // SEO problem!
844 $url_requested = ( isset( $_SERVER['REQUEST_URI'] ) ? filter_var( wp_unslash( $_SERVER['REQUEST_URI'] ), FILTER_SANITIZE_URL ) : '' );
845 }
846 if ( substr( $url_requested, 0, 2 ) === '/?' ) {
847 $url_requested = substr( $url_requested, 2 ); }
848 if ( '/' === $url_requested ) {
849 $url_requested = ''; }
850
851 // sanitize urldecode.
852 $url_requested = filter_var( $url_requested, FILTER_SANITIZE_URL );
853
854 return $url_requested;
855 }
856
857
858 /**
859 * Convert data us to default format di WordPress
860 *
861 * @param string $dt date to convert.
862 * @return converted data.
863 ****************************************************/
864 function nsp_hdate( $dt = '00000000' ) {
865 return mysql2date( get_option( 'date_format' ), substr( $dt, 0, 4 ) . '-' . substr( $dt, 4, 2 ) . '-' . substr( $dt, 6, 2 ) );
866 }
867
868
869 /**
870 * Get newstatpress_hdate
871 *
872 * @param string $dt the date.
873 * @return the hdate.
874 */
875 function newstatpress_hdate( $dt = '00000000' ) {
876 return mysql2date( get_option( 'date_format' ), nsp_my_substr( $dt, 0, 4 ) . '-' . nsp_my_substr( $dt, 4, 2 ) . '-' . nsp_my_substr( $dt, 6, 2 ) );
877 }
878
879
880
881 // ---------------------------------------------------------------------------
882 // GET DATA from visitors Functions
883 // ---------------------------------------------------------------------------
884
885
886 /**TODO clean $accepted
887 * Extracts the accepted language from browser headers
888 *
889 * @param string $accepted not used.
890 */
891 function nsp_get_language( $accepted ) {
892 if ( isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) {
893
894 // Capture up to the first delimiter (, found in Safari).
895 preg_match( '/([^,;]*)/', sanitize_text_field( wp_unslash( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ), $array_languages );
896
897 // Fix some codes, the correct syntax is with minus (-) not underscore (_).
898 return str_replace( '_', '-', strtolower( $array_languages[0] ) );
899 }
900 return 'xx'; // Indeterminable language.
901 }
902
903 /**
904 * Get query pairs
905 *
906 * @param string $url the url.
907 * @return the pairs.
908 */
909 function nsp_get_query_pairs( $url ) {
910 $parsed_url = wp_parse_url( $url );
911 $tab = wp_parse_url( $url );
912 $host = $tab['host'];
913 if ( key_exists( 'query', $tab ) ) {
914 $query = $tab['query'];
915 return explode( '&', $query );
916 } else {
917 return null;}
918 }
919
920
921 /**
922 * Get OS from the given argument
923 *
924 * @param string $arg the argument to parse for OS.
925 * @return the OS find in configuration file.
926 *******************************************/
927 function nsp_get_os( $arg ) {
928 global $newstatpress_dir;
929
930 $arg = str_replace( ' ', '', $arg );
931 $lines = file( $newstatpress_dir . '/def/os.dat' );
932 foreach ( $lines as $line_num => $os ) {
933 list($nome_os,$id_os) = explode( '|', $os );
934 if ( strpos( $arg, $id_os ) === false ) {
935 continue;
936 }
937 return $nome_os; // fount.
938 }
939 return '';
940 }
941
942 /**
943 * Get OS logo from the given argument
944 *
945 * @param string $arg the argument to parse for OS.
946 * @return the OS find in configuration file.
947 *******************************************/
948 function nsp_get_os_img( $arg ) {
949 global $newstatpress_dir;
950 $lines = file( $newstatpress_dir . '/def/os.dat' );
951 foreach ( $lines as $line_num => $os ) {
952 list($name_os,$id_os,$img_os) = explode( '|', $os );
953 if ( strcmp( $name_os, $arg ) == 0 ) {
954 return $img_os;
955 }
956 }
957 return '';
958 }
959
960 /**
961 * Get Browser from the given argument
962 *
963 * @param string $arg the argument to parse for Brower.
964 * @return the Browser find in configuration file.
965 ************************************************/
966 function nsp_get_browser( $arg ) {
967 global $newstatpress_dir;
968
969 $arg = str_replace( ' ', '', $arg );
970 $lines = file( $newstatpress_dir . '/def/browser.dat' );
971 foreach ( $lines as $line_num => $browser ) {
972 list($nome,$id) = explode( '|', $browser );
973 if ( strpos( $arg, $id ) === false ) {
974 continue;
975 }
976 return $nome; // fount.
977 }
978 return '';
979 }
980
981 /**
982 * Get Browser from the given argument
983 *
984 * @param string $arg the argument to parse for Brower.
985 * @return the Browser find in configuration file.
986 ************************************************/
987 function nsp_get_browser_img( $arg ) {
988 global $newstatpress_dir;
989 $lines = file( $newstatpress_dir . '/def/browser.dat' );
990 foreach ( $lines as $line_num => $browser ) {
991 list($name_browser,$id,$img_browser) = explode( '|', $browser );
992 if ( strcmp( $name_browser, $arg ) == 0 ) {
993 return $img_browser;
994 }
995 }
996 return '';
997 }
998
999 /**
1000 * Check if the given ip is to ban
1001 *
1002 * @param string $arg the ip to check.
1003 * @return '' id the address is banned.
1004 */
1005 function nsp_check_ban_ip( $arg ) {
1006 global $newstatpress_dir;
1007
1008 $lines = file( $newstatpress_dir . '/def/banips.dat' );
1009 foreach ( $lines as $line_num => $banip ) {
1010 if ( strpos( $arg, rtrim( $banip, "\n" ) ) === false ) {
1011 continue;
1012 }
1013 return ''; // this is banned.
1014 }
1015 return $arg;
1016 }
1017
1018 /**
1019 * Get the search engines
1020 *
1021 * @param string $referrer the url to test.
1022 * @return the search engine present in the url.
1023 */
1024 function nsp_get_se( $referrer = null ) {
1025 global $newstatpress_dir;
1026
1027 $key = null;
1028 $lines = file( $newstatpress_dir . '/def/searchengines.dat' );
1029 foreach ( $lines as $line_num => $se ) {
1030 list($nome,$url,$key) = explode( '|', $se );
1031 if ( strpos( $referrer, $url ) === false ) {
1032 continue;
1033 }
1034
1035 // find if.
1036 $variables = nsp_get_query_pairs( html_entity_decode( $referrer ) );
1037 null === $variables ? $i = 0 : $i = count( $variables );
1038 while ( $i-- ) {
1039 $tab = explode( '=', $variables[ $i ] );
1040 if ( $tab[0] === $key ) {
1041 return ( $nome . '|' . urldecode( $tab[1] ) );}
1042 }
1043 }
1044 return null;
1045 }
1046
1047 /**
1048 * Get the spider from the given agent
1049 *
1050 * @param string $agent the agent string.
1051 * @return agent the fount agent.
1052 *************************************/
1053 function nsp_get_spider( $agent = null ) {
1054 global $newstatpress_dir;
1055
1056 $agent = str_replace( ' ', '', $agent );
1057 $key = null;
1058 $lines = file( $newstatpress_dir . '/def/spider.dat' );
1059 foreach ( $lines as $line_num => $spider ) {
1060 list($nome,$key) = explode( '|', $spider );
1061 if ( strpos( $agent, $key ) === false ) {
1062 continue;
1063 }
1064 // fount.
1065 return $nome;
1066 }
1067 return null;
1068 }
1069
1070 /**
1071 * Get the previous month in 'YYYYMM' format
1072 *
1073 * @return the previous month.
1074 */
1075 function nsp_lastmonth() {
1076 $ta = getdate( current_time( 'timestamp' ) );
1077
1078 $year = $ta['year'];
1079 $month = $ta['mon'];
1080
1081 --$month; // go back 1 month.
1082
1083 if ( 0 == $month ) : // if this month is Jan.
1084 --$year; // go back a year.
1085 $month = 12; // last month is Dec.
1086 endif;
1087
1088 // return in format 'YYYYMM'.
1089 return sprintf( $year . '%02d', $month );
1090 }
1091
1092 /**
1093 * Create or update the table
1094 *
1095 * @param string $action to do: update, create.
1096 *************************************/
1097 function nsp_build_plugin_sql_table( $action ) {
1098
1099 global $wpdb;
1100 global $wp_db_version;
1101 $table_name = NSP_TABLENAME;
1102 $charset_collate = $wpdb->get_charset_collate();
1103 $index_list = array(
1104 array(
1105 'Key_name' => 'spider_nation',
1106 'Column_name' => '(spider, nation)',
1107 ),
1108 array(
1109 'Key_name' => 'ip_date',
1110 'Column_name' => '(ip, date)',
1111 ),
1112 array(
1113 'Key_name' => 'agent',
1114 'Column_name' => '(agent)',
1115 ),
1116 array(
1117 'Key_name' => 'search',
1118 'Column_name' => '(search)',
1119 ),
1120 array(
1121 'Key_name' => 'referrer',
1122 'Column_name' => '(referrer)',
1123 ),
1124 array(
1125 'Key_name' => 'feed_spider_os',
1126 'Column_name' => '(feed, spider, os)',
1127 ),
1128 array(
1129 'Key_name' => 'os',
1130 'Column_name' => '(os)',
1131 ),
1132 array(
1133 'Key_name' => 'date_feed_spider',
1134 'Column_name' => '(date, feed, spider)',
1135 ),
1136 array(
1137 'Key_name' => 'feed_spider_browser',
1138 'Column_name' => '(feed, spider, browser)',
1139 ),
1140 array(
1141 'Key_name' => 'browser',
1142 'Column_name' => '(browser)',
1143 ),
1144 );
1145 // Add by chab
1146 // IF the table is already created then DROP INDEX for update.
1147 if ( '' === $action ) {
1148 $action = 'create';
1149 }
1150
1151 $sql_createtable = '
1152 CREATE TABLE ' . $table_name . ' (
1153 id mediumint(9) NOT NULL AUTO_INCREMENT,
1154 date int(8),
1155 time time,
1156 ip varchar(39),
1157 urlrequested varchar(250),
1158 agent varchar(250),
1159 referrer varchar(512),
1160 search varchar(250),
1161 nation varchar(2),
1162 os varchar(30),
1163 browser varchar(32),
1164 searchengine varchar(16),
1165 spider varchar(32),
1166 feed varchar(8),
1167 user varchar(16),
1168 timestamp timestamp DEFAULT 0,
1169 UNIQUE KEY id (id)';
1170
1171 if ( 'create' === $action ) {
1172 foreach ( $index_list as $index ) {
1173 $key_name = $index['Key_name'];
1174 $column_name = $index['Column_name'];
1175 $sql_createtable .= ", INDEX $key_name $column_name";
1176 }
1177 } elseif ( 'update' === $action ) {
1178 foreach ( $index_list as $index ) {
1179 $key_name = $index['Key_name'];
1180 $column_name = $index['Column_name'];
1181 // db call ok; no-cache ok. unprepared SQL OK.
1182 // phpcs:ignore
1183 if ( $wpdb->query(
1184 // phpcs:ignore
1185 $wpdb->prepare( "SHOW INDEXES FROM `$table_name` WHERE Key_name = %s", $key_name ) // phpcs:ignore
1186 ) === '' ) {
1187 $sql_createtable .= ",\n INDEX $key_name $column_name";
1188 }
1189 }
1190 }
1191 $sql_createtable .= ") $charset_collate;";
1192
1193 if ( $wp_db_version >= 5540 ) {
1194 $page = 'wp-admin/includes/upgrade.php';
1195 } else {
1196 $page = 'wp-admin/upgrade-functions.php';
1197 }
1198
1199 require_once ABSPATH . $page;
1200 dbDelta( $sql_createtable );
1201 }
1202
1203 /**
1204 * Get if this is a feed
1205 *
1206 * @param string $url the url to test.
1207 * @return the kind of feed that is found.
1208 *****************************************/
1209 function nsp_is_feed( $url ) {
1210 $tmp = get_bloginfo( 'rdf_url' );
1211 if ( $tmp ) {
1212 if ( stristr( $url, $tmp ) !== false ) {
1213 return 'RDF'; }
1214 }
1215
1216 $tmp = get_bloginfo( 'rss2_url' );
1217 if ( $tmp ) {
1218 if ( stristr( $url, $tmp ) !== false ) {
1219 return 'RSS2'; }
1220 }
1221
1222 $tmp = get_bloginfo( 'rss_url' );
1223 if ( $tmp ) {
1224 if ( stristr( $url, $tmp ) !== false ) {
1225 return 'RSS'; }
1226 }
1227
1228 $tmp = get_bloginfo( 'atom_url' );
1229 if ( $tmp ) {
1230 if ( stristr( $url, $tmp ) !== false ) {
1231 return 'ATOM'; }
1232 }
1233
1234 $tmp = get_bloginfo( 'comments_rss2_url' );
1235 if ( $tmp ) {
1236 if ( stristr( $url, $tmp ) !== false ) {
1237 return 'COMMENT'; }
1238 }
1239
1240 $tmp = get_bloginfo( 'comments_atom_url' );
1241 if ( $tmp ) {
1242 if ( stristr( $url, $tmp ) !== false ) {
1243 return 'COMMENT'; }
1244 }
1245
1246 if ( stristr( $url, 'wp-feed.php' ) !== false ) {
1247 return 'RSS2'; }
1248 if ( stristr( $url, '/feed/' ) !== false ) {
1249 return 'RSS2'; }
1250 return '';
1251 }
1252
1253 /**
1254 * Insert statistic into the database
1255 ************************************/
1256 function nsp_stat_append() {
1257
1258 global $wpdb;
1259 $table_name = NSP_TABLENAME;
1260 global $userdata;
1261
1262 wp_get_current_user();
1263 $feed = '';
1264
1265 // Time.
1266 $timestamp = current_time( 'timestamp' );
1267 $vdate = gmdate( 'Ymd', $timestamp );
1268 $vtime = gmdate( 'H:i:s', $timestamp );
1269 $timestamp = gmdate( 'Y-m-d H:i:s', $timestamp );
1270
1271 // IP.
1272 if ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
1273 $ip_address = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ); // BASIC detection -> to delete if it works.
1274 }
1275
1276 // Is this IP blacklisted from file?
1277 if ( nsp_check_ban_ip( $ip_address ) === '' ) {
1278 return ''; }
1279
1280 // Is this IP blacklisted from user?
1281 $to_ignore = get_option( 'newstatpress_ignore_ip', array() );
1282 foreach ( $to_ignore as $a_ip_range ) {
1283 list ($ip_to_ignore, $mask) = @explode( '/', trim( $a_ip_range ) );
1284 if ( empty( $mask ) ) {
1285 $mask = 32;
1286 }
1287 $long_ip_to_ignore = ip2long( $ip_to_ignore );
1288 $long_mask = bindec( str_pad( '', $mask, '1' ) . str_pad( '', 32 - $mask, '0' ) );
1289 $long_masked_user_ip = ip2long( $ip_address ) & $long_mask;
1290 $long_masked_ip_to_ignore = $long_ip_to_ignore & $long_mask;
1291 if ( $long_masked_user_ip === $long_masked_ip_to_ignore ) {
1292 return ''; }
1293 }
1294
1295 if ( get_option( 'newstatpress_cryptip' ) === 'checked' ) {
1296 $ip_address = crypt( $ip_address, NSP_TEXTDOMAIN );
1297 }
1298
1299 // URL (requested).
1300 $url_requested = nsp_url();
1301 if ( preg_match( '/.ico$/i', $url_requested ) ) {
1302 return ''; }
1303 if ( preg_match( '/favicon.ico/i', $url_requested ) ) {
1304 return ''; }
1305 if ( preg_match( '/.css$/i', $url_requested ) ) {
1306 return ''; }
1307 if ( preg_match( '/.js$/i', $url_requested ) ) {
1308 return ''; }
1309 if ( stristr( $url_requested, content_url() ) !== false ) {
1310 return ''; }
1311 if ( stristr( $url_requested, admin_url() ) !== false ) {
1312 return ''; }
1313 $url_requested = esc_sql( $url_requested );
1314
1315 // Is a given permalink blacklisted?
1316 $to_ignore = get_option( 'newstatpress_ignore_permalink', array() );
1317 foreach ( $to_ignore as $a_filter ) {
1318 if ( ! empty( $url_requested ) && strpos( $url_requested, $a_filter ) === 0 ) {
1319 return ''; }
1320 }
1321
1322 $referrer = ( isset( $_SERVER['HTTP_REFERER'] ) ? htmlentities( sanitize_text_field( wp_unslash( $_SERVER['HTTP_REFERER'] ) ) ) : '' );
1323 $referrer = esc_url( $referrer );
1324 $referrer = esc_sql( $referrer );
1325
1326 $user_agent = ( isset( $_SERVER['HTTP_USER_AGENT'] ) ? htmlentities( sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) ) : '' );
1327 $user_agent = sanitize_text_field( $user_agent );
1328 $user_agent = esc_sql( $user_agent );
1329
1330 $spider = nsp_get_spider( $user_agent );
1331
1332 if ( ( '' !== $spider ) && ( get_option( 'newstatpress_donotcollectspider' ) === 'checked' ) ) {
1333 return ''; }
1334
1335 // ininitalize to empty.
1336 $searchengine = '';
1337 $search_phrase = '';
1338
1339 if ( '' !== $spider ) {
1340 $os = '';
1341 $browser = '';
1342 } else {
1343 // Trap feeds.
1344 if ( isset( $_SERVER['REQUEST_URI'] ) ) {
1345 $feed = nsp_is_feed( get_bloginfo( 'url' ) . sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
1346 }
1347 // Get OS and browser.
1348 $os = nsp_get_os( $user_agent );
1349 $browser = nsp_get_browser( $user_agent );
1350
1351 $exp_referrer = nsp_get_se( $referrer );
1352 if ( isset( $exp_referrer ) ) {
1353 list($searchengine,$search_phrase) = explode( '|', $exp_referrer );
1354 }
1355 }
1356
1357 // Country (ip2nation table) or language.
1358 $countrylang = '';
1359 if ( $wpdb->get_var( "SHOW TABLES LIKE 'ip2nation'" ) === 'ip2nation' ) {
1360 $qry = $wpdb->get_row(
1361 $wpdb->prepare(
1362 'SELECT *
1363 FROM ip2nation
1364 WHERE ip < INET_ATON( %s )
1365 ORDER BY ip DESC
1366 LIMIT 0,1',
1367 $ip_address
1368 )
1369 ); // db call ok; no-cache ok.
1370 if ( isset( $qry->country ) ) {
1371 $countrylang = $qry->country;
1372 }
1373 }
1374
1375 if ( '' === $countrylang ) {
1376 if ( isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) {
1377 $countrylang = nsp_get_language( sanitize_text_field( wp_unslash( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) );
1378 }
1379 }
1380
1381 // Auto-delete visits if...
1382 if ( get_option( 'newstatpress_autodelete' ) !== '' ) {
1383 $int = filter_var( get_option( 'newstatpress_autodelete' ), FILTER_SANITIZE_NUMBER_INT );
1384 // secure action.
1385 if ( $int >= 1 ) {
1386 $t = gmdate( 'Ymd', current_time( 'timestamp' ) - 86400 * $int * 30 );
1387 // phpcs:ignore -- db call ok; no-cache ok.
1388 $results = $wpdb->query(
1389 $wpdb->prepare(
1390 "DELETE FROM `$table_name`
1391 WHERE date < %s
1392 ",
1393 $t
1394 )
1395 ); // phpcs:ignore: unprepared SQL OK.
1396 }
1397 }
1398
1399 // Auto-delete spiders visits if...
1400 if ( get_option( 'newstatpress_autodelete_spiders' ) !== '' ) {
1401 $int = filter_var( get_option( 'newstatpress_autodelete_spiders' ), FILTER_SANITIZE_NUMBER_INT );
1402
1403 // secure action.
1404 if ( $int >= 1 ) {
1405 $t = gmdate( 'Ymd', current_time( 'timestamp' ) - 86400 * $int * 30 );
1406 // phpcs:ignore -- db call ok; no-cache ok.
1407 $results = $wpdb->query(
1408 $wpdb->prepare(
1409 "DELETE FROM `$table_name`
1410 WHERE date < %s and
1411 feed='' and
1412 spider<>''
1413 ",
1414 $t
1415 )
1416 ); // phpcs:ignore: unprepared SQL OK.
1417 }
1418 }
1419
1420 if ( ( ! is_user_logged_in() ) || ( get_option( 'newstatpress_collectloggeduser' ) === 'checked' ) ) {
1421 if ( is_user_logged_in() && ( get_option( 'newstatpress_collectloggeduser' ) === 'checked' ) ) {
1422 $current_user = wp_get_current_user();
1423
1424 // Is a given name to ignore?
1425 $to_ignore = get_option( 'newstatpress_ignore_users', array() );
1426 foreach ( $to_ignore as $a_filter ) {
1427 if ( $current_user->user_login === $a_filter ) {
1428 return ''; }
1429 }
1430 }
1431
1432 // phpcs:ignore -- db call ok; no-cache ok.
1433 if ( $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table_name ) ) !== $table_name ) {
1434 nsp_build_plugin_sql_table( 'create' );
1435 }
1436
1437 $login = $userdata ? $userdata->user_login : null;
1438
1439 $results = $wpdb->insert(
1440 $table_name,
1441 array(
1442 'date' => $vdate,
1443 'time' => $vtime,
1444 'ip' => substr( $ip_address, 0, 39 ),
1445 'urlrequested' => substr( $url_requested, 0, 250 ),
1446 'agent' => substr( wp_strip_all_tags( $user_agent ), 0, 250 ),
1447 'referrer' => substr( $referrer, 0, 512 ),
1448 'search' => substr( wp_strip_all_tags( $search_phrase ), 0, 250 ),
1449 'nation' => substr( $countrylang, 0, 2 ),
1450 'os' => substr( $os, 0, 30 ),
1451 'browser' => substr( $browser, 0, 32 ),
1452 'searchengine' => substr( $searchengine, 0, 16 ),
1453 'spider' => substr( $spider, 0, 32 ),
1454 'feed' => substr( $feed, 0, 8 ),
1455 'user' => substr( $login, 0, 16 ),
1456 'timestamp' => $timestamp,
1457 ),
1458 array( '%s' )
1459 );
1460 }
1461 }
1462 add_action( 'send_headers', 'nsp_stat_append' );
1463
1464 /**
1465 * Generate the Ajax code for the given variable
1466 *
1467 * @param string $var variable to get.
1468 * @param int $limit optional limit value for query.
1469 * @param string $flag optional flag value for checked.
1470 * @param string $url optional url address.
1471 ************************************************/
1472 function nsp_generate_ajax_var( $var, $limit = 0, $flag = '', $url = '' ) {
1473 global $newstatpress_dir;
1474 global $_newstatpress;
1475
1476 wp_enqueue_script( 'wp_ajax_nsp_variables_' . $var, plugins_url( './includes/js/nsp_variables_' . $var . '.js', __FILE__ ), array( 'jquery' ), $_newstatpress['version'], true );
1477 wp_localize_script(
1478 'wp_ajax_nsp_variables_' . $var,
1479 'nsp_variablesAjax_' . $var,
1480 array(
1481 'ajaxurl' => admin_url( 'admin-ajax.php' ),
1482 'postCommentNonce' => wp_create_nonce( 'newstatpress-nsp_variables-nonce' ),
1483 'VAR' => $var,
1484 'URL' => $url,
1485 'FLAG' => $flag,
1486 'LIMIT' => $limit,
1487 )
1488 );
1489
1490 $res = '<span id="' . $var . '">_</span>';
1491 return $res;
1492 }
1493
1494 /**
1495 * Return the expanded vars into the give code. API to use for users.
1496 *
1497 * @param string $body the body.
1498 */
1499 function newstatpress_print( $body = '' ) {
1500 return nsp_expand_vars_inside_code( $body );
1501 }
1502
1503 /**
1504 * Expand vars into the give code
1505 *
1506 * @param string $body the code where to look for variables to expand.
1507 * @return the modified code.
1508 ************************************************************/
1509 function nsp_expand_vars_inside_code( $body ) {
1510 global $wpdb;
1511 $table_name = NSP_TABLENAME;
1512
1513 $vars_list = array(
1514 'visits',
1515 'yvisits',
1516 'mvisits',
1517 'wvisits',
1518 'totalvisits',
1519 'totalpageviews',
1520 'todaytotalpageviews',
1521 'alltotalvisits',
1522 'monthtotalpageviews',
1523 );
1524
1525 // look for $vars_list.
1526 foreach ( $vars_list as $var ) {
1527 if ( strpos( strtolower( $body ), "%$var%" ) !== false ) {
1528 $body = str_replace( "%$var%", nsp_generate_ajax_var( $var ), $body );
1529 }
1530 }
1531
1532 // look for %thistotalvisits%.
1533 if ( strpos( strtolower( $body ), '%thistotalvisits%' ) !== false ) {
1534 $body = str_replace( '%thistotalvisits%', nsp_generate_ajax_var( 'thistotalvisits', 0, '', nsp_url() ), $body );
1535 }
1536
1537 // look for %since%.
1538 if ( strpos( strtolower( $body ), '%since%' ) !== false ) {
1539 // not needs prepare.
1540 // phpcs:ignore -- db call ok; no-cache ok.
1541 $qry = $wpdb->get_var(
1542 "SELECT date
1543 FROM `$table_name`
1544 ORDER BY date
1545 LIMIT 1
1546 "
1547 ); // phpcs:ignore: unprepared SQL OK.
1548 $body = str_replace( '%since%', nsp_hdate( $qry ), $body );
1549 }
1550
1551 // look for %os%.
1552 if ( strpos( strtolower( $body ), '%os%' ) !== false ) {
1553 $user_agent = ( isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '' );
1554 $os = nsp_get_os( $user_agent );
1555 $body = str_replace( '%os%', $os, $body );
1556 }
1557
1558 // look for %browser%.
1559 if ( strpos( strtolower( $body ), '%browser%' ) !== false ) {
1560 $browser = nsp_get_browser( $user_agent );
1561 $body = str_replace( '%browser%', $browser, $body );
1562 }
1563
1564 // look for %ip%.
1565 if ( strpos( strtolower( $body ), '%ip%' ) !== false ) {
1566 $ip_address = ( isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '' );
1567 $body = str_replace( '%ip%', $ip_address, $body );
1568 }
1569
1570 // look for %visitorsonline%.
1571 if ( strpos( strtolower( $body ), '%visitorsonline%' ) !== false ) {
1572 $act_time = current_time( 'timestamp' );
1573 $from_time = gmdate( 'Y-m-d H:i:s', strtotime( '-4 minutes', $act_time ) );
1574 $to_time = gmdate( 'Y-m-d H:i:s', $act_time );
1575 // use prepare.
1576 // phpcs:ignore -- db call ok; no-cache ok.
1577 $qry = $wpdb->get_var(
1578 $wpdb->prepare(
1579 "SELECT count(DISTINCT(ip)) AS visitors
1580 FROM `$table_name`
1581 WHERE
1582 spider='' AND
1583 feed='' AND
1584 date = %s AND
1585 timestamp BETWEEN %s AND %s
1586 ",
1587 gmdate( 'Ymd', $act_time ),
1588 $from_time,
1589 $to_time
1590 )
1591 ); // phpcs:ignore: unprepared SQL OK.
1592 $body = str_replace( '%visitorsonline%', $qry, $body );
1593 }
1594
1595 // look for %usersonline%.
1596 if ( strpos( strtolower( $body ), '%usersonline%' ) !== false ) {
1597 $act_time = current_time( 'timestamp' );
1598 $from_time = gmdate( 'Y-m-d H:i:s', strtotime( '-4 minutes', $act_time ) );
1599 $to_time = gmdate( 'Y-m-d H:i:s', $act_time );
1600 // use prepare.
1601 // phpcs:ignore -- db call ok; no-cache ok.
1602 $qry = $wpdb->get_var(
1603 $wpdb->prepare(
1604 "SELECT count(DISTINCT(ip)) AS users
1605 FROM `$table_name`
1606 WHERE
1607 spider='' AND
1608 feed='' AND
1609 date = %s AND
1610 user<>'' AND
1611 timestamp BETWEEN %s AND %s
1612 ",
1613 gmdate( 'Ymd', $act_time ),
1614 $from_time,
1615 $to_time
1616 )
1617 ); // phpcs:ignore: unprepared SQL OK.
1618 $body = str_replace( '%usersonline%', $qry, $body );
1619 }
1620
1621 // look for %toppost%.
1622 if ( strpos( strtolower( $body ), '%toppost%' ) !== false ) {
1623 // not needs prepare.
1624 // phpcs:ignore -- db call ok; no-cache ok.
1625 $qry = $wpdb->get_row(
1626 "SELECT urlrequested,count(*) AS totale
1627 FROM `$table_name`
1628 WHERE
1629 spider='' AND
1630 feed='' AND
1631 urlrequested LIKE '%p=%'
1632 GROUP BY urlrequested
1633 ORDER BY totale DESC
1634 LIMIT 1
1635 "
1636 ); // phpcs:ignore: unprepared SQL OK.
1637 $body = str_replace( '%toppost%', nsp_decode_url( $qry->urlrequested ), $body );
1638 }
1639
1640 // look for %topbrowser%.
1641 if ( strpos( strtolower( $body ), '%topbrowser%' ) !== false ) {
1642 // not needs prepare.
1643 // phpcs:ignore -- db call ok; no-cache ok.
1644 $qry = $wpdb->get_row(
1645 "SELECT browser,count(*) AS totale
1646 FROM `$table_name`
1647 WHERE
1648 spider='' AND
1649 feed=''
1650 GROUP BY browser
1651 ORDER BY totale DESC
1652 LIMIT 1
1653 "
1654 ); // phpcs:ignore: unprepared SQL OK.
1655 $body = str_replace( '%topbrowser%', nsp_decode_url( $qry->browser ), $body );
1656 }
1657
1658 // look for %topos%.
1659 if ( strpos( strtolower( $body ), '%topos%' ) !== false ) {
1660 // not needs prepare.
1661 // phpcs:ignore -- db call ok; no-cache ok.
1662 $qry = $wpdb->get_row(
1663 "SELECT os,count(*) AS totale
1664 FROM `$table_name`
1665 WHERE
1666 spider='' AND
1667 feed=''
1668 GROUP BY os
1669 ORDER BY totale DESC
1670 LIMIT 1
1671 "
1672 ); // phpcs:ignore: unprepared SQL OK.
1673 $body = str_replace( '%topos%', nsp_decode_url( $qry->os ), $body );
1674 }
1675
1676 // look for %topsearch%.
1677 if ( strpos( strtolower( $body ), '%topsearch%' ) !== false ) {
1678 // not needs prepare.
1679 // phpcs:ignore -- db call ok; no-cache ok.
1680 $qry = $wpdb->get_row(
1681 "SELECT search, count(*) AS csearch
1682 FROM `$table_name`
1683 WHERE
1684 search<>''
1685 GROUP BY search
1686 ORDER BY csearch DESC
1687 LIMIT 1
1688 "
1689 ); // phpcs:ignore: unprepared SQL OK.
1690 if ( is_object( $qry ) ) {
1691 $body = str_replace( '%topsearch%', nsp_decode_url( $qry->search ), $body );
1692 } else {
1693 $body = str_replace( '%topsearch%', '', $body );
1694 }
1695 }
1696
1697 return $body;
1698 }
1699
1700 // TODO : if working, move the contents into the caller instead of this function.
1701 /**
1702 * Get top posts
1703 *
1704 * @param int $limit the number of post to show.
1705 * @param string $showcounts if checked show totals.
1706 * @return result of extraction
1707 *******************************************/
1708 function nsp_top_posts( $limit = 5, $showcounts = 'checked' ) {
1709 return nsp_generate_ajax_var( 'widget_topposts', $limit, $showcounts );
1710 }
1711
1712
1713 /**
1714 * Build NewsStatPress Widgets: Stat and TopPosts
1715 *
1716 * @param string $args arguments.
1717 ************************************************/
1718 function nsp_widget_init( $args ) {
1719 if ( ! function_exists( 'wp_register_sidebar_widget' ) || ! function_exists( 'wp_register_widget_control' ) ) {
1720 return;
1721 }
1722
1723 /**
1724 * Statistics Widget control.
1725 */
1726 function nsp_widget_stats_control() {
1727 global $nsp_widget_vars;
1728 $options = get_option( 'widget_newstatpress' );
1729 if ( ! is_array( $options ) ) {
1730 $options = array(
1731 'title' => 'NewStatPress Stats',
1732 'body' => 'Visits today: %visits%',
1733 );
1734 }
1735 if ( isset( $_POST['newstatpress-submit'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['newstatpress-submit'] ) ), 'nsp_widget_stats_control' ) ) {
1736 if ( isset( $_POST['newstatpress-title'] ) ) {
1737 $options['title'] = sanitize_text_field( wp_unslash( $_POST['newstatpress-title'] ) );
1738 }
1739 if ( isset( $_POST['newstatpress-body'] ) ) {
1740 $options['body'] = stripslashes( sanitize_text_field( wp_unslash( $_POST['newstatpress-body'] ) ) );
1741 }
1742 update_option( 'widget_newstatpress', $options );
1743 }
1744 $title = htmlspecialchars( $options['title'], ENT_QUOTES );
1745 $body = htmlspecialchars( $options['body'], ENT_QUOTES );
1746
1747 // the form.
1748 echo "<p>
1749 <label for='newstatpress-title'>" . esc_html__( 'Title:', 'newstatpress' ) . "</label>
1750 <input class='widget-title' id='newstatpress-title' name='newstatpress-title' type='text' value='" . esc_attr( $title ) . "' />
1751 </p>
1752 <p>
1753 <label for='newstatpress-body'>" . esc_html_e( 'Body:', 'newstatpress' ) . "</label>
1754 <textarea class='widget-body' id='newstatpress-body' name='newstatpress-body' type='textarea' placeholder='Example: Month visits: %mvisits%...'>" . esc_html( $body ) . '</textarea>
1755 </p>
1756 ' . "
1757 <input type='hidden' id='newstatpress-submit' name='newstatpress-submit' value='" . esc_html( wp_create_nonce( 'nsp_widget_stats_control' ) ) . "' />
1758 <p>" . esc_html__( 'Stats available: ', 'newstatpress' ) . "<br/ >
1759 <span class='widget_varslist'>";
1760 foreach ( $nsp_widget_vars as $var ) {
1761 echo "<a href='#'>%" . esc_html( $var[0] ) . '% <span>';
1762 esc_html( $var[1] );
1763 echo '</span></a> | ';
1764 }
1765 echo '</span></p>';
1766 }
1767
1768 /**
1769 * Widget stats
1770 *
1771 * @param string $args arguments.
1772 */
1773 function nsp_widget_stats( $args ) {
1774 $options = get_option( 'widget_newstatpress' );
1775 $title = esc_js( $options['title'] );
1776 $body = esc_js( $options['body'] );
1777 echo wp_kses_post( $args['before_widget'] );
1778 print( wp_kses_post( $args['before_title'] ) . esc_html( $title ) . wp_kses_post( $args['after_title'] ) );
1779 print wp_kses_post( nsp_expand_vars_inside_code( $body ) );
1780 echo wp_kses_post( $args['after_widget'] );
1781 }
1782 wp_register_sidebar_widget( 'NewStatPress', 'NewStatPress Stats', 'nsp_widget_stats' );
1783 wp_register_widget_control( 'NewStatPress', array( 'NewStatPress', 'widgets' ), 'nsp_widget_stats_control', 300, 210 );
1784
1785 /**
1786 * Top posts Widget control.
1787 */
1788 function nsp_widget_top_posts_control() {
1789 $options = get_option( 'widget_newstatpresstopposts' );
1790 if ( ! is_array( $options ) ) {
1791 $options = array(
1792 'title' => 'NewStatPress TopPosts',
1793 'howmany' => '5',
1794 'showcounts' => 'checked',
1795 );
1796 }
1797 if ( isset( $_POST['newstatpresstopposts-submit'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['newstatpresstopposts-submit'] ) ), 'nsp_widget_top_posts_control' ) ) {
1798 if ( isset( $_POST['newstatpresstopposts-title'] ) ) {
1799 $options['title'] = sanitize_text_field( wp_unslash( $_POST['newstatpresstopposts-title'] ) );
1800 }
1801 if ( isset( $_POST['newstatpresstopposts-howmany'] ) ) {
1802 $options['howmany'] = filter_var( wp_unslash( $_POST['newstatpresstopposts-howmany'] ), FILTER_SANITIZE_NUMBER_INT );
1803 }
1804 if ( isset( $_POST['newstatpresstopposts-showcounts'] ) ) {
1805 $options['showcounts'] = sanitize_text_field( wp_unslash( $_POST['newstatpresstopposts-showcounts'] ) );
1806 }
1807 if ( '1' === $options['showcounts'] ) {
1808 $options['showcounts'] = 'checked';
1809 }
1810 update_option( 'widget_newstatpresstopposts', $options );
1811 }
1812 $title = htmlspecialchars( $options['title'], ENT_QUOTES );
1813 $howmany = htmlspecialchars( $options['howmany'], ENT_QUOTES );
1814 $showcounts = htmlspecialchars( $options['showcounts'], ENT_QUOTES );
1815 // the form.
1816 echo "<p style='text-align:right;'>
1817 <label for='newstatpresstopposts-title'>" . esc_html__( 'Title', 'newstatpress' ) . "
1818 <input style='width: 250px;' id='newstatpress-title' name='newstatpresstopposts-title' type='text' value='" . esc_attr( $title ) . "' />
1819 </label>
1820 </p>
1821 <p style='text-align:right;'>
1822 <label for='newstatpresstopposts-howmany'>" . esc_html__( 'Limit results to', 'newstatpress' ) . "
1823 <input style='width: 100px;' id='newstatpresstopposts-howmany' name='newstatpresstopposts-howmany' type='text' value='" . esc_attr( $howmany ) . "' />
1824 </label>
1825 </p>";
1826 echo '<p style="text-align:right;"><label for="newstatpresstopposts-showcounts">' . esc_html__( 'Visits', 'newstatpress' ) . ' <input id="newstatpresstopposts-showcounts" name="newstatpresstopposts-showcounts" type=checkbox value="checked" ' . esc_attr( $showcounts ) . ' /></label></p>';
1827 echo '<input type="hidden" id="newstatpress-submitTopPosts" name="newstatpresstopposts-submit" value="' . esc_html( wp_create_nonce( 'nsp_widget_top_posts_control' ) ) . '" />';
1828 }
1829
1830 /**
1831 * Widget top posts
1832 *
1833 * @param string $args args to use.
1834 */
1835 function nsp_widget_top_posts( $args ) {
1836 $options = get_option( 'widget_newstatpresstopposts' );
1837 $title = htmlspecialchars( $options['title'], ENT_QUOTES );
1838 $howmany = htmlspecialchars( $options['howmany'], ENT_QUOTES );
1839 $showcounts = htmlspecialchars( $options['showcounts'], ENT_QUOTES );
1840 echo wp_kses_post( $args['before_widget'] );
1841 print( wp_kses_post( $args['before_title'] ) . esc_html( $title ) . wp_kses_post( $args['after_title'] ) );
1842 print wp_kses_post( nsp_top_posts( $howmany, $showcounts ) );
1843 echo wp_kses_post( $args['after_widget'] );
1844 }
1845 wp_register_sidebar_widget( 'NewStatPressTopPosts', 'NewStatPress TopPosts', 'nsp_widget_top_posts' );
1846 wp_register_widget_control( 'NewStatPressTopPosts', array( 'NewStatPressTopPosts', 'widgets' ), 'nsp_widget_top_posts_control', 300, 110 );
1847 }
1848 add_action( 'plugins_loaded', 'nsp_widget_init' );
1849
1850
1851 /**
1852 * Calculate variations
1853 *
1854 * @param int $month month.
1855 * @param int $lmonth lmonth.
1856 */
1857 function nsp_calculate_variation( $month, $lmonth ) {
1858
1859 $target = round(
1860 $month / (
1861 ( gmdate( 'd', current_time( 'timestamp' ) ) - 1 +
1862 ( gmdate( 'H', current_time( 'timestamp' ) ) +
1863 ( gmdate( 'i', current_time( 'timestamp' ) ) + 1 ) / 60.0 ) / 24.0 ) ) * gmdate( 't', current_time( 'timestamp' ) )
1864 );
1865
1866 $monthchange = null;
1867 $added = null;
1868
1869 if ( 0 <> $lmonth ) {
1870 $percent_change = round( 100 * ( $month / $lmonth ) - 100, 1 );
1871 $percent_target = round( 100 * ( $target / $lmonth ) - 100, 1 );
1872
1873 if ( $percent_change >= 0 ) {
1874 $percent_change = sprintf( "+%'04.1f", $percent_change );
1875 $monthchange = "<td class='coll'><code style='color:green'>($percent_change%)</code></td>";
1876 } else {
1877 $percent_change = sprintf( "%'05.1f", $percent_change );
1878 $monthchange = "<td class='coll'><code style='color:red'>($percent_change%)</code></td>";
1879 }
1880
1881 if ( $percent_target >= 0 ) {
1882 $percent_target = sprintf( "+%'04.1f", $percent_target );
1883 $added = "<td class='coll'><code style='color:green'>($percent_target%)</code></td>";
1884 } else {
1885 $percent_target = sprintf( "%'05.1f", $percent_target );
1886 $added = "<td class='coll'><code style='color:red'>($percent_target%)</code></td>";
1887 }
1888 } else {
1889 $monthchange = '<td></td>';
1890 $added = "<td class='coll'></td>";
1891 }
1892
1893 $calculated_result = array( $monthchange, $target, $added );
1894 return $calculated_result;
1895 }
1896
1897 register_activation_hook( __FILE__, 'nsp_build_plugin_sql_table' );
1898 ?>
1899