-
Notifications
You must be signed in to change notification settings - Fork 0
/
counter-core.php
1635 lines (1395 loc) · 57.8 KB
/
counter-core.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Filename: counter-core.php
* Count Per Day - core functions
*/
include_once('safe.php');
if (!defined('ABSPATH'))
exit;
/**
* include GeoIP addon if available
*/
$cpd_geoip_dir = WP_CONTENT_DIR . '/count-per-day-geoip/';
if (file_exists($cpd_geoip_dir . 'geoip.inc') && filesize($cpd_geoip_dir . 'geoip.inc') > 1000) // not empty
include_once('geoip.php');
$cpd_geoip = (class_exists('GeoIp') && file_exists($cpd_geoip_dir . 'GeoIP.dat') && filesize($cpd_geoip_dir . 'GeoIP.dat') > 1000) ? 1 : 0;
/**
* helper functions
*/
class CountPerDayCore {
var $options; // options array
var $dir; // this plugin dir
var $dbcon; // database connection
var $queries = []; // queries times for debug
var $page; // Post/Page-ID
var $installed = false; // CpD installed in subblogs?
/**
* Windows server < PHP 5.3
* PHP without IPv6 support
*/
static function inetPton($ip) {
// convert to IPv6 e.g. '::62.149.142.175' or '62.149.142.175'
if (strpos($ip, '.') !== false) {
$ip = explode(':', $ip);
$ip = $ip[ count($ip) - 1 ];
$ip = explode('.', $ip);
$ip = '::FFFF:' . sprintf("%'.02s", dechex($ip[0])) . sprintf("%'.02s", dechex($ip[1])) . ':' . sprintf("%'.02s", dechex($ip[2])) . sprintf("%'.02s", dechex($ip[3]));
}
// IPv6
if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
$ip = explode(':', $ip);
$parts = 8 - count($ip);
$res = '';
$replaced = 0;
foreach ($ip as $seg) {
if ($seg != '')
$res .= str_pad($seg, 4, '0', STR_PAD_LEFT);
elseif ($replaced == 0) {
for ($i = 0; $i <= $parts; $i++)
$res .= '0000';
$replaced = 1;
} elseif ($replaced == 1)
$res .= '0000';
}
$ip = pack('H' . strlen($res), $res);
} else
// Dummy IP if no valid IP found
$ip = inetPton('127.0.0.1');
return $ip;
}
/**
* Constructor
*/
function init() {
// variables
global $wpdb, $path, $cpd_dir_name;
define('CPD_METABOX', 'cpd_metaboxes');
// multisite table names
foreach (['cpd_counter', 'cpd_counter_useronline', 'cpd_notes'] as $t) {
$wpdb->tables[] = $t;
$wpdb->$t = $wpdb->get_blog_prefix() . $t;
}
// use local time, not UTC
get_option('gmt_offset');
$this->options = get_option('count_per_day');
// manual debug mode
if (true === is_input('debug') && WP_DEBUG)
$this->options['debug'] = 1;
$this->dir = plugins_url('/' . $cpd_dir_name);
$this->queries[0] = 0;
// update online counter
add_action('wp', [&$this, 'deleteOnlineCounter']);
// settings link on plugin page
add_filter('plugin_action_links', [&$this, 'pluginActions'], 10, 2);
// auto counter
if ($this->options['autocount'])
add_action('wp', [&$this, 'count']);
// javascript to count cached posts
if ($this->options['ajax']) {
add_action('wp_enqueue_scripts', [&$this, 'addJquery']);
add_action('wp_footer', [&$this, 'addAjaxScript']);
}
if (is_admin()) {
// admin menu
add_action('admin_menu', [&$this, 'menu']);
// widget on dashboard page
add_action('wp_dashboard_setup', [&$this, 'dashboardWidgetSetup']);
// CpD dashboard page
add_filter('screen_layout_columns', [&$this, 'screenLayoutColumns'], 10, 2);
// CpD dashboard
add_action('admin_menu', [&$this, 'setAdminMenu']);
// counter column posts lists
add_action('admin_head', [&$this, 'addPostTypesColumns']);
// adds javascript
add_action('admin_head', [&$this, 'addJS']);
// check version
add_action('admin_head', [&$this, 'checkInstalledVersion']);
}
// locale support
load_plugin_textdomain('cpd', false, $cpd_dir_name . '/locale');
// adds stylesheet
if (is_admin())
add_action('admin_head', [&$this, 'addCss']);
if (empty($this->options['no_front_css']))
add_action('wp_head', [&$this, 'addCss']);
// widget setup
add_action('widgets_init', [&$this, 'register_widgets']);
// activation hook
register_activation_hook(ABSPATH . PLUGINDIR . '/count-per-day/counter.php', [&$this, 'checkVersion']);
// update hook
if (function_exists('register_update_hook'))
register_update_hook(ABSPATH . PLUGINDIR . '/count-per-day/counter.php', [&$this, 'checkVersion']);
// uninstall hook
register_uninstall_hook($path . 'counter.php', 'count_per_day_uninstall');
// query times debug
if ($this->options['debug']) {
add_action('wp_footer', [&$this, 'showQueries']);
add_action('admin_footer', [&$this, 'showQueries']);
}
// add shortcode support
$this->addShortcodes();
// thickbox in backend only
if (false !== strpos(get_input_server_string('SCRIPT_NAME'), '/wp-admin/'))
add_action('admin_enqueue_scripts', [&$this, 'addThickbox']);
$this->aton = 'INET_ATON';
$this->ntoa = 'INET_NTOA';
// include scripts
if (is_admin()) {
add_action('init', [&$this, 'addCpdIncludes']);
}
}
/**
* adds some shortcodes to use functions in frontend
*/
function addShortcodes() {
add_shortcode('CPD_READS_THIS', [&$this, 'shortShow']);
add_shortcode('CPD_READS_TOTAL', [&$this, 'shortReadsTotal']);
add_shortcode('CPD_READS_TODAY', [&$this, 'shortReadsToday']);
add_shortcode('CPD_READS_YESTERDAY', [&$this, 'shortReadsYesterday']);
add_shortcode('CPD_READS_LAST_WEEK', [&$this, 'shortReadsLastWeek']);
add_shortcode('CPD_READS_PER_MONTH', [&$this, 'shortReadsPerMonth']);
add_shortcode('CPD_READS_THIS_MONTH', [&$this, 'shortReadsThisMonth']);
add_shortcode('CPD_VISITORS_TOTAL', [&$this, 'shortUserAll']);
add_shortcode('CPD_VISITORS_ONLINE', [&$this, 'shortUserOnline']);
add_shortcode('CPD_VISITORS_TODAY', [&$this, 'shortUserToday']);
add_shortcode('CPD_VISITORS_YESTERDAY', [&$this, 'shortUserYesterday']);
add_shortcode('CPD_VISITORS_LAST_WEEK', [&$this, 'shortUserLastWeek']);
add_shortcode('CPD_VISITORS_THIS_MONTH', [&$this, 'shortUserThisMonth']);
add_shortcode('CPD_VISITORS_PER_DAY', [&$this, 'shortUserPerDay']);
add_shortcode('CPD_FIRST_COUNT', [&$this, 'shortFirstCount']);
add_shortcode('CPD_CLIENTS', [&$this, 'shortClients']);
add_shortcode('CPD_VISITORS_PER_MONTH', [&$this, 'shortUserPerMonth']);
add_shortcode('CPD_VISITORS_PER_POST', [&$this, 'shortUserPerPost']);
add_shortcode('CPD_COUNTRIES', [&$this, 'shortCountries']);
add_shortcode('CPD_COUNTRIES_USERS', [&$this, 'shortCountriesUsers']);
add_shortcode('CPD_MOST_VISITED_POSTS', [&$this, 'shortMostVisitedPosts']);
add_shortcode('CPD_REFERERS', [&$this, 'shortReferers']);
add_shortcode('CPD_POSTS_ON_DAY', [&$this, 'shortPostsOnDay']);
add_shortcode('CPD_MAP', [&$this, 'shortShowMap']);
add_shortcode('CPD_DAY_MOST_READS', [&$this, 'shortDayWithMostReads']);
add_shortcode('CPD_DAY_MOST_USERS', [&$this, 'shortDayWithMostUsers']);
add_shortcode('CPD_SEARCHSTRINGS', [&$this, 'shortGetSearches']);
add_shortcode('CPD_FLOTCHART', [&$this, 'shortFlotChart']);
}
/**
* include scripts
*/
function addCpdIncludes() {
global $count_per_day, $wpdb, $cpd_geoip, $cpd_geoip_dir;
if (false === is_input('page')) return;
switch (get_input_string('page')) {
case 'cpd_notes':
include_once('notes.php');
exit;
case 'cpd_massbots':
include_once('massbots.php');
exit;
case 'cpd_userperspan':
include_once('userperspan.php');
exit;
case 'cpd_map':
include_once('map/map.php');
exit;
case 'cpd_ajax':
include_once('ajax.php');
exit;
case 'cpd_download':
include_once('download.php');
exit;
}
}
/**
* adds counter columns to posts list
*/
function addPostTypesColumns() {
$post_types = get_post_types(['public' => true], 'objects');
foreach ($post_types as $post_type) {
$name = trim($post_type->name);
add_action('manage_' . $name . 's_custom_column', [&$this, 'cpdColumnContent'], 10, 2);
add_filter('manage_edit-' . $name . '_columns', [&$this, 'cpdColumn']);
}
}
function addJquery() {
wp_enqueue_script('jquery');
}
function addThickbox() {
wp_enqueue_script('thickbox');
}
/**
* update DB if neccessary
*/
function checkInstalledVersion() {
global $cpd_version, $cpd_dir_name;
if ($this->options['version'] != $cpd_version) {
$this->checkVersion();
echo '<div class="updated">
<p>' . sprintf(__('"Count per Day" updated to version %s.', 'cpd'), $cpd_version) . '</p>
<p>' . sprintf(__('Please check the %s section!', 'cpd'), '<a href="options-general.php?page=count-per-day%2Fcounter-options.php&tab=tools">GeoIP</a>') . '</p>
</div>';
}
}
/**
* checks installation in sub blogs
*/
function checkVersion() {
global $wpdb;
if (true === function_exists('is_multisite')
&& true === is_multisite()
&& true === is_input('networkwide')
&& "" !== get_input_string('networkwide')
) {
$old_blog = $wpdb->blogid;
$blogids = $wpdb->get_col($wpdb->prepare("SELECT blog_id FROM %s", $wpdb->blogs));
foreach ($blogids as $blog_id) { // create tables in all sub blogs
switch_to_blog($blog_id);
$this->createTables();
}
switch_to_blog($old_blog);
return;
}
$this->createTables(); // create tables in main blog
}
/**
* creates tables if not exists
*/
function createTables() {
global $wpdb;
// for plugin activation, creates $wpdb
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
// variables for subblogs
$cpd_c = $wpdb->cpd_counter;
$cpd_o = $wpdb->cpd_counter_useronline;
$cpd_n = $wpdb->cpd_notes;
if (!empty ($wpdb->charset))
$charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
if (!empty ($wpdb->collate))
$charset_collate .= " COLLATE $wpdb->collate";
// table "counter"
$sql = "CREATE TABLE IF NOT EXISTS `$cpd_c` (
`id` int(10) NOT NULL auto_increment,
`ip` int(10) unsigned NOT NULL,
`client` varchar(500) NOT NULL,
`date` date NOT NULL,
`page` mediumint(9) NOT NULL,
`country` CHAR(2) NOT NULL,
`referer` varchar(500) NOT NULL,
PRIMARY KEY (`id`),
KEY `idx_page` (`page`),
KEY `idx_dateip` (`date`,`ip`) )
$charset_collate";
$this->mysqlQuery('', $sql, 'createTables ' . __LINE__);
// update fields in old table
$field = $this->mysqlQuery('rows', "SHOW FIELDS FROM `$cpd_c` LIKE 'ip'", 'createTables ' . __LINE__);
$row = $field[0];
if (strpos(strtolower($row->Type), 'int') === false) {
$queries = [
"ALTER TABLE `$cpd_c` ADD `ip2` INT(10) UNSIGNED NOT NULL AFTER `ip`",
"UPDATE `$cpd_c` SET ip2 = $this->aton(ip)",
"ALTER TABLE `$cpd_c` DROP `ip`",
"ALTER TABLE `$cpd_c` CHANGE `ip2` `ip` INT( 10 ) UNSIGNED NOT NULL",
"ALTER TABLE `$cpd_c` CHANGE `date` `date` date NOT NULL",
"ALTER TABLE `$cpd_c` CHANGE `page` `page` mediumint(9) NOT NULL",
"ALTER TABLE `$cpd_c` CHANGE `client` `client` VARCHAR( 250 ) NOT NULL",
"ALTER TABLE `$cpd_c` CHANGE `referer` `referer` VARCHAR( 250 ) NOT NULL"
];
foreach ($queries as $sql)
$this->mysqlQuery('', $sql, 'update old fields ' . __LINE__);
}
// change textfield limit
$sql = "ALTER TABLE `$cpd_c`
CHANGE `client` `client` VARCHAR( 500 ) NOT NULL ,
CHANGE `referer` `referer` VARCHAR( 500 ) NOT NULL;";
$this->mysqlQuery('', $sql, 'change textfield limit ' . __LINE__);
// make new keys
$keys = $this->mysqlQuery('rows', "SHOW KEYS FROM `$cpd_c`", 'make keys ' . __LINE__);
$s = [];
foreach ($keys as $row)
if ($row->Key_name != 'PRIMARY')
$s[] = "DROP INDEX `$row->Key_name`";
$s = array_unique($s);
$sql = "ALTER TABLE `$cpd_c` ";
if (sizeof($s))
$sql .= implode(',', $s) . ', ';
$sql .= 'ADD KEY `idx_dateip` (`date`,`ip`), ADD KEY `idx_page` (`page`)';
$this->mysqlQuery('', $sql, 'make keys ' . __LINE__);
// delete table "counter-online", since v3.0
$this->mysqlQuery('', "DROP TABLE IF EXISTS `$cpd_o`", 'table online ' . __LINE__);
// delete table "notes", since v3.0
if (!get_option('count_per_day_notes')) {
$table = $this->mysqlQuery('rows', "SHOW TABLES LIKE '$cpd_n'", 'table notes ' . __LINE__);
if (!empty($table)) {
$ndb = $this->mysqlQuery('rows', "SELECT * FROM $cpd_n", 'table notes ' . __LINE__);
$n = [];
foreach ($ndb as $note)
$n[] = [$note->date, $note->note];
update_option('count_per_day_notes', $n);
}
}
$this->mysqlQuery('', "DROP TABLE IF EXISTS `$cpd_n`", 'table notes ' . __LINE__);
// update options to array
$this->updateOptions();
}
/**
* get result from database
*
* @param string $kind kind of result
* @param string|array $sql sql query [and args]
* @param string $func name for debug info
*/
function mysqlQuery($kind = '', $sql = '', $func = '') {
global $wpdb;
if (empty($sql))
return;
$t = microtime(true);
if (is_array($sql)) {
$sql = array_shift($sql);
$args = $sql;
$preparedSql = $wpdb->prepare($sql, $args);
} else
$preparedSql = $sql;
if (empty($preparedSql))
return;
$r = false;
if ($kind == 'var')
$r = $wpdb->get_var($preparedSql);
else if ($kind == 'count')
$r = $wpdb->get_var('SELECT COUNT(*) FROM (' . trim($preparedSql, ';') . ') t');
else if ($kind == 'rows')
$r = $wpdb->get_results($preparedSql);
else
$wpdb->query($preparedSql);
if ($this->options['debug']) {
$con = $wpdb->dbh;
$errno = (isset($con->errno)) ? $con->errno : mysqli_errno($con);
$error = (isset($con->error)) ? $con->error : mysqli_error($con);
$d = number_format(microtime(true) - $t, 5);
$m = sprintf("%.2f", memory_get_usage() / 1048576) . ' MB';
$error = (!$r && $errno) ? '<b style="color:red">ERROR:</b> ' . $errno . ' - ' . $error . ' - ' : '';
$this->queries[] = $func . " : <b>$d</b> - $m<br/><code>$kind - $preparedSql</code><br/>$error";
$this->queries[0] += $d;
}
return $r;
}
/**
* combines the options to one array, update from previous versions
*/
function updateOptions() {
global $cpd_version;
$o = get_option('count_per_day', []);
$this->options = ['version' => $cpd_version];
$odefault = [
'onlinetime' => 300,
'user' => 0,
'user_level' => 0,
'autocount' => 1,
'bots' => "bot\nspider\nsearch\ncrawler\nask.com\nvalidator\nsnoopy\nsuchen.de\nsuchbaer.de\nshelob\nsemager\nxenu\nsuch_de\nia_archiver\nMicrosoft URL Control\nnetluchs",
'dashboard_posts' => 20,
'dashboard_last_posts' => 20,
'dashboard_last_days' => 7,
'show_in_lists' => 1,
'chart_days' => 60,
'chart_height' => 200,
'countries' => 20,
'exclude_countries' => '',
'startdate' => '',
'startcount' => '',
'startreads' => '',
'anoip' => 0,
'massbotlimit' => 25,
'clients' => 'Firefox, Edge, MSIE, Chrome, Safari, Opera',
'ajax' => 0,
'debug' => 0,
'referers' => 1,
'referers_cut' => 0,
'fieldlen' => 150,
'localref' => 1,
'dashboard_referers' => 20,
'referers_last_days' => 7,
'no_front_css' => 0,
'whocansee' => 'publish_posts',
'backup_part' => 10000
];
foreach ($odefault as $k => $v)
$this->options[ $k ] = (isset($o[ $k ])) ? $o[ $k ] : $v;
update_option('count_per_day', $this->options);
}
/**
* anonymize IP address (last bit) if option is set
*
* @param $ip real IP address
*
* @return new IP address
*/
function anonymize_ip($ip) {
// only IPv4
if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4))
return $ip;
if ($this->options['debug'])
$this->queries[] = 'called Function: <b style="color:blue">anonymize_ip</b> IP: <code>' . $ip . '</code>';
if ($this->options['anoip']) {
$i = explode('.', $ip);
if (isset($i[3])) {
$i[3] += round(array_sum($i) / 4 + date_i18n('d'));
if ($i[3] > 255)
$i[3] -= 255;
}
return implode('.', $i);
} else
return $ip;
}
/**
* bot or human?
*
* @param string $client USER_AGENT
* @param array $bots strings to check
* @param string $ip IP adress
* @param string $ref referrer
*/
function isBot($client = '', $bots = '', $ip = '', $ref = '') {
if (empty($client) && is_input_server('HTTP_USER_AGENT'))
$client = get_input_server_string('HTTP_USER_AGENT');
if (empty($ip))
$ip = get_input_server_string('REMOTE_ADDR');
if (empty($ref) && is_input_server('HTTP_REFERER'))
$ref = get_input_server_string('HTTP_REFERER');
// empty/short client -> not normal browser -> bot
if (empty($client) || strlen($client) < 20)
return true;
if (empty($bots))
$bots = explode("\n", $this->options['bots']);
$isBot = false;
foreach ($bots as $bot) {
if (!$isBot) // loop until first bot was found only
{
$b = trim($bot);
if (!empty($b)
&& (
$ip == $b
|| strpos($ip, $b) === 0
|| strpos(strtolower($client), strtolower($b)) !== false
|| strpos(strtolower($ref), strtolower($b)) !== false
)
)
$isBot = true;
}
}
return $isBot;
}
/**
* calls widget class
*/
function register_widgets() {
register_widget('CountPerDay_Widget');
register_widget('CountPerDay_PopularPostsWidget');
}
/**
* shows debug infos
*/
function showQueries() {
global $wpdb, $cpd_path, $cpd_version, $cpd_geoip_dir;
$serverinfo = (isset($wpdb->dbh->server_info)) ? $wpdb->dbh->server_info : mysql_get_server_info($wpdb->dbh);
$clientinfo = (isset($wpdb->dbh->client_info)) ? $wpdb->dbh->client_info : mysql_get_client_info();
echo '<div style="position:absolute;margin:10px;padding:10px;border:1px red solid;background:#fff;clear:both">
<b>Count per Day - DEBUG: ' . round($this->queries[0], 3) . ' s</b><ol>' . "\n";
echo '<li>'
. '<b>Server:</b> ' . get_input_server_string('SERVER_SOFTWARE') . '<br/>'
. '<b>PHP:</b> ' . phpversion() . '<br/>'
. '<b>mySQL Server:</b> ' . $serverinfo . '<br/>'
. '<b>mySQL Client:</b> ' . $clientinfo . '<br/>'
. '<b>WordPress:</b> ' . get_bloginfo('version') . '<br/>'
. '<b>Count per Day:</b> ' . $cpd_version . '<br/>'
. '<b>Time for Count per Day:</b> ' . date_i18n('Y-m-d H:i') . '<br/>'
. '<b>URL:</b> ' . get_input_server_string('SERVER_NAME') . get_input_server_string('REQUEST_URI') . '<br/>'
. '<b>Referrer:</b> ' . (true === is_input_server('HTTP_REFERER') ? htmlentities(get_input_server_string('HTTP_REFERER')) : '') . '<br/>'
. '<b>PHP-Memory:</b> peak: ' . $this->formatBytes(memory_get_peak_usage()) . ', limit: ' . ini_get('memory_limit')
. '</li>';
echo "\n<li><b>POST:</b><br/>\n";
var_dump(json_encode(
$_POST
,
0
| JSON_HEX_APOS // All ' are converted to \u0027.
| JSON_HEX_QUOT // All " are converted to \u0022.
| JSON_HEX_AMP // All &#38;s are converted to \u0026.
| JSON_HEX_TAG // All < and > are converted to \u003C and \u003E.
| JSON_NUMERIC_CHECK // Encodes numeric strings as numbers.
| JSON_PRETTY_PRINT // Use whitespace in returned data to format it
));
echo '</li>';
echo '</li>';
echo "\n<li><b>Table:</b><br /><b>$wpdb->cpd_counter</b>:\n";
$res = $this->mysqlQuery('rows', "SHOW FIELDS FROM `$wpdb->cpd_counter`", 'showFields');
foreach ($res as $c)
echo '<span style="color:blue">' . $c->Field . '</span> = ' . $c->Type . ' ';
echo "\n</li>";
echo "\n<li><b>Options:</b><br />\n";
foreach ($this->options as $k => $v)
if ($k != 'bots') // hoster restrictions
echo "$k = $v<br />\n";
echo "</li>";
foreach ($this->queries as $q)
if ($q != $this->queries[0])
echo "\n<li>$q</li>";
echo "</ol>\n";
?>
<p>GeoIP:
dir=<?php echo substr(decoct(fileperms($cpd_geoip_dir)), -3) ?>
file=<?php echo (is_file($cpd_geoip_dir . 'GeoIP.dat')) ? substr(decoct(fileperms($cpd_geoip_dir . 'GeoIP.dat')), -3) : '-'; ?>
fopen=<?php echo (function_exists('fopen')) ? 'true' : 'false' ?>
gzopen=<?php echo (function_exists('gzopen')) ? 'true' : 'false' ?>
allow_url_fopen=<?php echo (ini_get('allow_url_fopen')) ? 'true' : 'false' ?>
</p>
<?php
echo '</div>';
}
/**
* formats byte integer to e.g. x.xx MB
*/
function formatBytes($size) {
$units = [' B', ' KB', ' MB', ' GB', ' TB'];
for ($i = 0; $size >= 1024 && $i < 4; $i++)
$size /= 1024;
return round($size, 2) . $units[ $i ];
}
/**
* adds style sheet to admin header
*/
function addCss() {
global $text_direction;
echo "\n" . '<link rel="stylesheet" href="' . $this->dir . '/counter.css" type="text/css" />' . "\n";
if ($text_direction == 'rtl')
echo "\n" . '<link rel="stylesheet" href="' . $this->dir . '/counter-rtl.css" type="text/css" />' . "\n";
// thickbox style here because add_thickbox() breaks RTL in he_IL
if (strpos(get_input_server_string('SCRIPT_NAME'), '/wp-admin/') !== false)
echo '<link rel="stylesheet" href="' . get_bloginfo('wpurl') . '/wp-includes/js/thickbox/thickbox.css" type="text/css" />' . "\n";
}
/**
* adds javascript to admin header
*/
function addJS() {
if (strpos(get_input_server_string('QUERY_STRING'), 'cpd_metaboxes') !== false)
echo '<!--[if IE]><script type="text/javascript" src="' . $this->dir . '/js/excanvas.min.js"></script><![endif]-->' . "\n";
}
/**
* adds ajax script to count cached posts
*/
function addAjaxScript() {
$this->getPostID();
$wp = ADMIN_COOKIE_PATH;
echo <<< JSEND
<script type="text/javascript">
// Count per Day
//<![CDATA[
var cpdTime = new Date().getTime() / 1000;
jQuery(document).ready( function()
{
jQuery.get('{$wp}/?page=cpd_ajax&f=count&cpage={$this->page}&time='+cpdTime, function(text)
{
var cpd_funcs = text.split('|');
for(var i = 0; i < cpd_funcs.length; i++)
{
var cpd_daten = cpd_funcs[i].split('===');
var cpd_field = document.getElementById('cpd_number_' + cpd_daten[0].toLowerCase());
if (cpd_field != null) { cpd_field.innerHTML = cpd_daten[1]; }
}
});
} );
//]]>
</script>
JSEND;
}
/**
* gets PostID
*/
function getPostID() {
global $wp_query;
// find PostID
if (!is_404()) :
// index, date, search and other "list" pages will count only once
$p = 0;
if ($this->options['autocount'] && is_singular()) {
// single page with autocount on
// make loop before regular loop is defined
if (have_posts()) :
while (have_posts() && empty($p)) :
the_post();
$p = get_the_ID();
endwhile;
endif;
rewind_posts();
} else if (is_singular())
// single page with template tag show() or count()
$p = get_the_ID();
// "index" pages only with autocount
else if (is_category() || is_tag())
// category or tag => negativ ID in CpD DB
$p = 0 - $wp_query->get_queried_object_id();
$this->page = $p;
if ($this->options['debug'])
$this->queries[] = 'called Function: <b style="color:blue">getPostID</b> page ID: <code>' . $p . '</code>';
return $p;
endif;
return false;
}
/**
* deletes spam in table, if you add new bot pattern you can clean the db
*/
function cleanDB() {
global $wpdb;
// get trimed bot array
function trim_value(&$value) { $value = trim($value); }
$bots = explode("\n", $this->options['bots']);
array_walk($bots, 'trim_value');
$rows_before = $this->mysqlQuery('var', "SELECT COUNT(*) FROM $wpdb->cpd_counter", 'cleanDB ' . __LINE__);
// delete by ip
foreach ($bots as $ip)
if (intval($ip) > 0)
$this->mysqlQuery('', "DELETE FROM $wpdb->cpd_counter WHERE {$this->ntoa}(ip) LIKE '" . $ip . "%'", 'clenaDB_ip ' . __LINE__);
// delete by client
foreach ($bots as $bot)
if (intval($bot) == 0)
$this->mysqlQuery('', "DELETE FROM $wpdb->cpd_counter WHERE client LIKE '%" . $bot . "%'", 'cleanDB_client ' . __LINE__);
// delete if a previously countered page was deleted
$this->mysqlQuery('', "DELETE FROM $wpdb->cpd_counter WHERE page NOT IN ( SELECT id FROM $wpdb->posts) AND page > 0", 'cleanDB_delPosts ' . __LINE__);
$rows_after = $this->mysqlQuery('var', "SELECT COUNT(*) FROM $wpdb->cpd_counter", 'cleanDB ' . __LINE__);
return $rows_before - $rows_after;
}
/**
* adds menu entry to backend
*
* @param string $content WP-"Content"
*/
function menu($content) {
global $cpd_dir_name;
if (function_exists('add_options_page')) {
$menutitle = 'Count per Day';
add_options_page('CountPerDay', $menutitle, 'manage_options', $cpd_dir_name . '/counter-options.php');
}
}
/**
* adds an "settings" link to the plugins page
*/
function pluginActions($links, $file) {
global $cpd_dir_name;
if ($file == $cpd_dir_name . '/counter.php'
&& strpos(get_input_server_string('SCRIPT_NAME'), '/network/') === false
) // not on network plugin page
{
$link = '<a href="options-general.php?page=' . $cpd_dir_name . '/counter-options.php">' . __('Settings') . '</a>';
array_unshift($links, $link);
}
return $links;
}
/**
* adds widget to dashboard page
*/
function dashboardWidgetSetup() {
$can_see = str_replace(
// administrator, editor, author, contributor, subscriber
[10, 7, 2, 1, 0],
['manage_options', 'moderate_comments', 'edit_published_posts', 'edit_posts', 'read'],
$this->options['show_in_lists']);
if (current_user_can($can_see))
wp_add_dashboard_widget('cpdDashboardWidget', 'Count per Day', [&$this, 'dashboardWidget']);
}
/**
* sets columns on dashboard page
*/
function screenLayoutColumns($columns, $screen) {
if (isset($this->pagehook) && $screen == $this->pagehook)
$columns[ $this->pagehook ] = 4;
return $columns;
}
/**
* extends the admin menu
*/
function setAdminMenu() {
$menutitle = 'Count per Day';
$this->pagehook = add_submenu_page('index.php', 'CountPerDay', $menutitle, $this->options['whocansee'], CPD_METABOX, [&$this, 'onShowPage']);
add_action('load-' . $this->pagehook, [&$this, 'onLoadPage']);
}
/**
* backlink to Plugin homepage
*/
function cpdInfo() {
global $cpd_version;
$t = '<span style="white-space:nowrap">' . date_i18n('Y-m-d H:i') . '</span>';
echo '<p style="margin:0">Count per Day: <code>' . $cpd_version . '</code><br/>';
printf(__('Time for Count per Day: <code>%s</code>.', 'cpd'), $t);
echo '<br />' . __('Bug? Problem? Question? Hint? Praise?', 'cpd') . ' ';
printf(__('Write a comment on the <a href="%s">plugin page</a>.', 'cpd'), 'http://www.tomsdimension.de/wp-plugins/count-per-day');
echo '<br />' . __('License') . ': <a href="http://www.tomsdimension.de/postcards">Postcardware :)</a>';
echo '<br /><a href="' . $this->dir . '/readme.txt?KeepThis=true&TB_iframe=true" title="Count per Day - Readme.txt" class="thickbox"><strong>Readme.txt</strong></a></p>';
}
/**
* function calls from metabox default parameters
*/
function getMostVisitedPostsMeta() { $this->getMostVisitedPosts(); }
function getUserPerPostMeta() { $this->getUserPerPost(); }
function getVisitedPostsOnDayMeta() { $this->getVisitedPostsOnDay(0, 100); }
function dashboardChartMeta() { $this->dashboardChart(0, false, false); }
function dashboardChartVisitorsMeta() { $this->dashboardChartVisitors(0, false, false); }
function getCountriesMeta() { $this->getCountries(0, false); }
function getCountriesVisitorsMeta() { $this->getCountries(0, false, true); }
function getReferersMeta() { $this->getReferers(0, false, 0); }
function getUserOnlineMeta() { $this->getUserOnline(false, true); }
function getUserPerMonthMeta() { $this->getUserPerMonth(); }
function getReadsPerMonthMeta() { $this->getReadsPerMonth(); }
function getSearchesMeta() { $this->getSearches(); }
/**
* will be executed if wordpress core detects this page has to be rendered
*/
function onLoadPage() {
global $cpd_geoip;
// needed javascripts
wp_enqueue_script('common');
wp_enqueue_script('wp-lists');
wp_enqueue_script('postbox');
// add the metaboxes
add_meta_box('reads_at_all', '<span class="cpd_icon cpd_summary"> </span> ' . __('Total visitors', 'cpd'), [&$this, 'dashboardReadsAtAll'], $this->pagehook, 'cpdrow1', 'core');
add_meta_box('user_online', '<span class="cpd_icon cpd_online"> </span> ' . __('Visitors online', 'cpd'), [&$this, 'getUserOnlineMeta'], $this->pagehook, 'cpdrow1', 'default');
add_meta_box('user_per_month', '<span class="cpd_icon cpd_user"> </span> ' . __('Visitors per month', 'cpd'), [&$this, 'getUserPerMonthMeta'], $this->pagehook, 'cpdrow2', 'default');
add_meta_box('reads_per_month', '<span class="cpd_icon cpd_reads"> </span> ' . __('Reads per month', 'cpd'), [&$this, 'getReadsPerMonthMeta'], $this->pagehook, 'cpdrow3', 'default');
add_meta_box('reads_per_post', '<span class="cpd_icon cpd_post"> </span> ' . __('Visitors per post', 'cpd'), [&$this, 'getUserPerPostMeta'], $this->pagehook, 'cpdrow3', 'default');
add_meta_box('last_reads', '<span class="cpd_icon cpd_calendar"> </span> ' . __('Latest Counts', 'cpd'), [&$this, 'getMostVisitedPostsMeta'], $this->pagehook, 'cpdrow4', 'default');
add_meta_box('day_reads', '<span class="cpd_icon cpd_day"> </span> ' . __('Visitors per day', 'cpd'), [&$this, 'getVisitedPostsOnDayMeta'], $this->pagehook, 'cpdrow4', 'default');
add_meta_box('searches', '<span class="cpd_icon cpd_help"> </span> ' . __('Search strings', 'cpd'), [&$this, 'getSearchesMeta'], $this->pagehook, 'cpdrow1', 'default');
add_meta_box('cpd_info', '<span class="cpd_icon cpd_help"> </span> ' . __('Plugin'), [&$this, 'cpdInfo'], $this->pagehook, 'cpdrow1', 'low');
if ($this->options['referers']) {
add_meta_box('browsers', '<span class="cpd_icon cpd_computer"> </span> ' . __('Browsers', 'cpd'), [&$this, 'getClients'], $this->pagehook, 'cpdrow2', 'default');
add_meta_box('referers', '<span class="cpd_icon cpd_referrer"> </span> ' . __('Referrer', 'cpd'), [&$this, 'getReferersMeta'], $this->pagehook, 'cpdrow3', 'default');
}
if ($cpd_geoip) {
add_meta_box('countries', '<span class="cpd_icon cpd_reads"> </span> ' . __('Reads per Country', 'cpd'), [&$this, 'getCountriesMeta'], $this->pagehook, 'cpdrow2', 'default');
add_meta_box('countries2', '<span class="cpd_icon cpd_user"> </span> ' . __('Visitors per Country', 'cpd'), [&$this, 'getCountriesVisitorsMeta'], $this->pagehook, 'cpdrow2', 'default');
}
}
/**
* creates dashboard page
*/
function onShowPage() {
global $screen_layout_columns, $count_per_day;
if (empty($screen_layout_columns))
$screen_layout_columns = 4;
$data = '';
?>
<div id="cpd-metaboxes" class="wrap">
<h2><img src="<?php echo $count_per_day->img('cpd_logo.png') ?>" alt="Logo" class="cpd_logo"
style="margin-left:8px"/> Count per Day - <?php _e('Statistics', 'cpd') ?></h2>
<?php
wp_nonce_field('cpd-metaboxes');
wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false);
wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false);
$css = 'style="width:' . round(100 / $screen_layout_columns, 1) . '%;"';
$this->getFlotChart();
?>
<div id="dashboard-widgets" class="metabox-holder cpd-dashboard">
<div
class="postbox-container" <?php echo $css; ?>><?php do_meta_boxes($this->pagehook, 'cpdrow1', $data); ?></div>
<div
class="postbox-container" <?php echo $css; ?>><?php do_meta_boxes($this->pagehook, 'cpdrow2', $data); ?></div>
<div
class="postbox-container" <?php echo $css; ?>><?php do_meta_boxes($this->pagehook, 'cpdrow3', $data); ?></div>
<div
class="postbox-container" <?php echo $css; ?>><?php do_meta_boxes($this->pagehook, 'cpdrow4', $data); ?></div>
<br class="clear"/>
</div>
</div>
<script type="text/javascript">
//<![CDATA[
jQuery(document).ready(function () {
jQuery('.if-js-closed').removeClass('if-js-closed').addClass('closed');
postboxes.add_postbox_toggles('<?php echo $this->pagehook; ?>');
});
//]]>
</script>
<?php
}
/**
* gets image recource with given name
*/
function img($r) {
return trailingslashit($this->dir) . 'img/' . $r;
}
function shortShow() { return $this->show('', '', false, false); }
function shortReadsTotal() { return $this->getReadsAll(true); }
function shortReadsToday() { return $this->getReadsToday(true); }
function shortReadsYesterday() { return $this->getReadsYesterday(true); }
function shortReadsThisMonth() { return $this->getReadsThisMonth(true); }
function shortReadsLastWeek() { return $this->getReadsLastWeek(true); }
function shortReadsPerMonth() { return $this->getReadsPerMonth(true, true); }
function shortUserAll() { return $this->getUserAll(true); }
function shortUserOnline() { return $this->getUserOnline(false, false, true); }
function shortUserToday() { return $this->getUserToday(true); }
function shortUserYesterday() { return $this->getUserYesterday(true); }
function shortUserLastWeek() { return $this->getUserLastWeek(true); }
function shortUserThisMonth() { return $this->getUserThisMonth(true); }
function shortUserPerDay() { return $this->getUserPerDay($this->options['dashboard_last_days'], true); }
function shortFirstCount() { return $this->getFirstCount(true); }
function shortClients() { return $this->getClients(true); }
function shortUserPerMonth() { return $this->getUserPerMonth(true, true); }
function shortUserPerPost() { return $this->getUserPerPost(0, true, true); }
function shortCountries() { return $this->getCountries(0, true, false, true); }
function shortCountriesUsers() { return $this->getCountries(0, true, true, true); }
function shortReferers() { return $this->getReferers(0, true, 0); }
function shortDayWithMostReads() { return $this->getDayWithMostReads(true, true); }
function shortDayWithMostUsers() { return $this->getDayWithMostUsers(true, true); }
function shortFlotChart() { return $this->getFlotChart(); }
function shortMostVisitedPosts($atts) {
extract(shortcode_atts([
'days' => 0,
'limit' => 0,
'postsonly' => 0,
'posttypes' => ''
], $atts));
return $this->getMostVisitedPosts($days, $limit, true, $postsonly, false, $posttypes);
}
function shortGetSearches($atts) {
extract(shortcode_atts([
'limit' => 0,
'days' => 0
], $atts));
return $this->getSearches($limit, $days, true);
}
function shortPostsOnDay($atts) {
extract(shortcode_atts([
'date' => 0,