PluginProbe
NewStatPress / trunk
NewStatPress vtrunk
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 trunk, at newstatpress.php

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