PluginProbe
NewStatPress / 1.3.8
NewStatPress v1.3.8
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.3.8, at newstatpress.php

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