-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ProcessPageViewStat.module
1815 lines (1693 loc) · 78 KB
/
ProcessPageViewStat.module
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 namespace ProcessWire;
/**
* Page View Statistic for ProcessWire
* Logs page views of the CMS.
*
* @author tech-c.net
* @license Licensed under GNU/GPL v2
* @link https://tech-c.net/posts/page-view-statistic-for-processwire/
* @version 1.2.4
*
* @see Forum Thread: https://processwire.com/talk/topic/24189-pageviewstatistic-for-processwire/
* @see Donate: https://tech-c.net/donation/
*/
class ProcessPageViewStat extends Process {
const dbTableMain = 'process_pageviewstat_main';
const dbTableIp = 'process_pageviewstat_ip';
const dbTableCountry = 'process_pageviewstat_country';
const dbTableBrowser = 'process_pageviewstat_browser';
const dbTableOs = 'process_pageviewstat_os';
const dbTablePage = 'process_pageviewstat_page';
const dbTableOrigin = 'process_pageviewstat_origin';
const dbTableCache = 'process_pageviewstat_cache';
const PageName = 'processpageviews';
const PagePermission = 'processpageviews';
const ChartMaxSize = 150;
const ViewDetailedRecords = 0;
const ViewDaysOfMonth = 1;
const ViewLast30Days = 2;
const ViewLast60Days = 3;
const ViewLast90Days = 4;
const ViewLast180Days = 5;
const ViewLast365Days = 6;
const ViewAllDays = 7;
const ViewMonthsOfYear = 8;
const ViewLast12Months = 9;
const ViewAllMonths = 10;
const ViewAllYears = 11;
private $init_time = 0;
/**
* Return information about this module
*/
public static function getModuleInfo() {
return array(
'title' => 'Page View Statistic',
'summary' => 'Logs page views of the CMS.',
'href' => 'https://tech-c.net/posts/page-view-statistic-for-processwire/',
'author' => 'tech-c.net',
'version' => 124,
'icon' => 'signal',
'permission' => self::PagePermission,
'autoload' => true,
'singular' => true);
}
/**
* Instance of ProcessPageViewStat
*/
public function __construct() {
$data = $this->modules->getModuleConfigData('ProcessPageViewStat');
if (((isset($data['delete_all_records'])) && ($data['delete_all_records'] != '')) ||
((isset($data['rebuild_cache'])) && ($data['rebuild_cache'] != ''))) {
$data['delete_all_records'] = '';
$data['rebuild_cache'] = '';
$this->modules->saveModuleConfigData('ProcessPageViewStat', $data);
}
}
/**
* Called only when the module is installed
*/
public function ___install () {
$sql = 'CREATE TABLE IF NOT EXISTS '.self::dbTableMain.' ('.
'id int(10) unsigned NOT NULL AUTO_INCREMENT,'.
'tm timestamp NOT NULL,'.
'vt int(10) unsigned,'.
'performance float unsigned,'.
'usr int(10) unsigned,'.
'ip_id int(10) unsigned,'.
'country_id int(10) unsigned,'.
'browser_id int(10) unsigned,'.
'os_id int(10) unsigned,'.
'page_id int(10) unsigned,'.
'origin_id int(10) unsigned,'.
'PRIMARY KEY(id)'.
') ENGINE='.$this->wire('config')->dbEngine.' DEFAULT CHARSET='.$this->wire('config')->dbCharset.';'.
'CREATE TABLE IF NOT EXISTS '.self::dbTableIp.' ('.
'id int(10) unsigned NOT NULL AUTO_INCREMENT,'.
'ip varchar(50),'.
'PRIMARY KEY(id),'.
'UNIQUE INDEX(ip)'.
') ENGINE='.$this->wire('config')->dbEngine.' DEFAULT CHARSET='.$this->wire('config')->dbCharset.';'.
'CREATE TABLE IF NOT EXISTS '.self::dbTableCountry.' ('.
'id int(10) unsigned NOT NULL AUTO_INCREMENT,'.
'country varchar(255),'.
'countryimg varchar(16),'.
'PRIMARY KEY(id),'.
'UNIQUE INDEX(country)'.
') ENGINE='.$this->wire('config')->dbEngine.' DEFAULT CHARSET='.$this->wire('config')->dbCharset.';'.
'CREATE TABLE IF NOT EXISTS '.self::dbTableBrowser.' ('.
'id int(10) unsigned NOT NULL AUTO_INCREMENT,'.
'browser varchar(255),'.
'browserimg varchar(16),'.
'PRIMARY KEY(id),'.
'UNIQUE INDEX(browser)'.
') ENGINE='.$this->wire('config')->dbEngine.' DEFAULT CHARSET='.$this->wire('config')->dbCharset.';'.
'CREATE TABLE IF NOT EXISTS '.self::dbTableOs.' ('.
'id int(10) unsigned NOT NULL AUTO_INCREMENT,'.
'os varchar(255),'.
'osimg varchar(16),'.
'PRIMARY KEY(id),'.
'UNIQUE INDEX(os)'.
') ENGINE='.$this->wire('config')->dbEngine.' DEFAULT CHARSET='.$this->wire('config')->dbCharset.';'.
'CREATE TABLE IF NOT EXISTS '.self::dbTablePage.' ('.
'id int(10) unsigned NOT NULL AUTO_INCREMENT,'.
'page varchar(255),'.
'PRIMARY KEY(id),'.
'UNIQUE INDEX(page)'.
') ENGINE='.$this->wire('config')->dbEngine.' DEFAULT CHARSET='.$this->wire('config')->dbCharset.';'.
'CREATE TABLE IF NOT EXISTS '.self::dbTableOrigin.' ('.
'id int(10) unsigned NOT NULL AUTO_INCREMENT,'.
'origin varchar(255),'.
'PRIMARY KEY(id),'.
'UNIQUE INDEX(origin)'.
') ENGINE='.$this->wire('config')->dbEngine.' DEFAULT CHARSET='.$this->wire('config')->dbCharset.';'.
'CREATE TABLE IF NOT EXISTS '.self::dbTableCache.' ('.
'id int(10) unsigned NOT NULL AUTO_INCREMENT,'.
'tm timestamp NOT NULL,'.
'counts int(10) unsigned,'.
'PRIMARY KEY(id),'.
'UNIQUE INDEX(tm)'.
') ENGINE='.$this->wire('config')->dbEngine.' DEFAULT CHARSET='.$this->wire('config')->dbCharset.';';
$this->database->query($sql);
$pages = $this->wire('pages');
$info = self::getModuleInfo();
$p = $pages->get('template=admin, name='.self::PageName);
if ($p->id) {
$p->delete();
$this->message('Deleted Page: '.$p->path);
}
$page = new Page();
$page->template = 'admin';
$page->parent = $pages->get($this->config->adminRootPageID)->child('name=setup');
$page->title = $info['title'];
$page->name = self::PageName;
$page->process = $this;
$page->save();
$this->message('Created Page: '.$page->path);
$p = $this->wire('permissions')->get(self::PagePermission);
if ($p->id) {
$p->delete();
$this->message('Deleted Permission: '.self::PagePermission);
}
$permission = new Permission();
$permission->name = self::PagePermission;
$permission->title = $info['title'];
$permission->save();
$this->message('Created Permission: '.self::PagePermission);
}
/**
* Called only when the module is uninstalled
*/
public function ___uninstall () {
$sql = 'DROP TABLE IF EXISTS '.self::dbTableMain.';'.
'DROP TABLE IF EXISTS '.self::dbTableIp.';'.
'DROP TABLE IF EXISTS '.self::dbTableCountry.';'.
'DROP TABLE IF EXISTS '.self::dbTableBrowser.';'.
'DROP TABLE IF EXISTS '.self::dbTableOs.';'.
'DROP TABLE IF EXISTS '.self::dbTablePage.';'.
'DROP TABLE IF EXISTS '.self::dbTableOrigin.';'.
'DROP TABLE IF EXISTS '.self::dbTableCache.';';
$this->database->query($sql);
$pages = $this->wire('pages');
$moduleID = $this->wire('modules')->getModuleID($this);
$mbPage = $pages->get('template=admin, process='.$moduleID.', name='.self::PageName);
if ($mbPage->id) {
$mbPage->delete();
$this->message('Deleted Page: '.$mbPage->path);
}
$permission = $this->wire('permissions')->get(self::PagePermission);
if ($permission->id){
$permission->delete();
$this->message('Deleted Permission: '.self::PagePermission);
}
}
/**
* Called only when the module is upgraded
*/
public function ___upgrade($fromVersion, $toVersion) {
try {
$query = $this->database->prepare('ALTER TABLE '.self::dbTableMain.' ADD COLUMN usr int(10) unsigned');
if (!$query->execute()) {
wire('log')->error($this->className.' Upgrade '.$fromVersion.' > '.$toVersion.': Unable to alter database table.');
} else {
wire('log')->message($this->className.' Upgrade '.$fromVersion.' > '.$toVersion.': Added column usr to '.self::dbTableMain);
}
} catch (\Exception $e) {
// Column exists already
}
try {
$query = $this->database->prepare('ALTER TABLE '.self::dbTableMain.' ADD COLUMN performance float unsigned');
if (!$query->execute()) {
wire('log')->error($this->className.' Upgrade '.$fromVersion.' > '.$toVersion.': Unable to alter database table.');
} else {
wire('log')->message($this->className.' Upgrade '.$fromVersion.' > '.$toVersion.': Added column performance to '.self::dbTableMain);
}
} catch (\Exception $e) {
// Column exists already
}
}
/**
* Initialization function called before any execute functions
*/
public function init() {
$this->init_time = microtime(true);
$this->addHookAfter('Page::render', $this, 'ProcessPageViewHook');
$this->addHookAfter('Modules::saveConfig', $this, 'ProcessPageViewSaveConfig');
if ($this->record_time == 1) {
$this->addHookBefore('ProcessPageView::pageNotFound', $this, 'ProcessPageViewReceiver');
}
if ($this->wire('modules')->isInstalled('LazyCron')) {
if ($this->auto_delete_older > 1) {
$this->addHook('LazyCron::everyDay', $this, 'ProcessPageViewAutoDelete');
}
if ($this->auto_update_ip2loc == 1) {
$this->addHook('LazyCron::every4Weeks', $this, 'ProcessPageViewIPlocUpdate');
}
if (in_array($this->cache_update_interval, array('everyMinute', 'every5Minutes', 'every10Minutes', 'every30Minutes', 'everyHour', 'everyDay'))) {
$this->addHook('LazyCron::'.$this->cache_update_interval, $this, 'ProcessPageViewCacheUpdate');
}
}
}
/**
* Truncates records or cache table if requested
*/
public function ProcessPageViewSaveConfig(HookEvent $event) {
if ((isset($event->arguments[0])) && ($event->arguments[0] == $this->className)) {
if ($this->input->post->rebuild_cache) {
$this->database->query('TRUNCATE TABLE '.self::dbTableCache);
$this->update_cache();
if ($this->enable_logging == 1) {
wire('log')->save($this->className, 'Cache rebuild');
}
}
if ($this->input->post->delete_all_records) {
$this->database->query('TRUNCATE TABLE '.self::dbTableMain);
$this->database->query('TRUNCATE TABLE '.self::dbTableIp);
$this->database->query('TRUNCATE TABLE '.self::dbTableCountry);
$this->database->query('TRUNCATE TABLE '.self::dbTableBrowser);
$this->database->query('TRUNCATE TABLE '.self::dbTableOs);
$this->database->query('TRUNCATE TABLE '.self::dbTablePage);
$this->database->query('TRUNCATE TABLE '.self::dbTableOrigin);
if ($this->enable_logging == 1) {
wire('log')->save($this->className, 'All records deleted');
}
}
}
}
/**
* Automatically deletes older records
*/
public function ProcessPageViewAutoDelete(HookEvent $event) {
if ($this->auto_delete_older > 1) {
$this->update_cache();
$dt = new \DateTime('now', new \DateTimeZone('UTC'));
$dt->modify('-'.$this->auto_delete_older.' days');
$utcfrom = $dt->format('U'); // EXPLAIN DELETE FROM <- test
$query = $this->database->prepare('DELETE FROM '.self::dbTableMain.' WHERE tm < FROM_UNIXTIME(:utcfrom)');
$query->bindValue(':utcfrom', (int) $utcfrom, \PDO::PARAM_STR);
if (!$query->execute()) {
if ($this->enable_logging == 1) {
wire('log')->save($this->className, 'Automatically delete records: '.$query->errorCode().' '.print_r($query->errorInfo(), true));
}
} else {
if ($this->enable_logging == 1) {
$count = $query->rowCount();
if ($count > 0) {
wire('log')->save($this->className, 'Automatically deleted '.$count.' records older than '.$this->auto_delete_older.' days');
}
}
}
}
}
/**
* Automatically download IP2Location database
*/
public function ProcessPageViewIPlocUpdate(HookEvent $event) {
require_once(__DIR__.'/func/IPlocUpdate.php');
$result = \ProcessPageViewStat\auto_download('https://download.ip2location.com/lite/IP2LOCATION-LITE-DB1.BIN.ZIP', __DIR__.'/iploc/', 'IP2LOCATION-LITE-DB1.BIN.ZIP');
if ($this->enable_logging == 1) {
wire('log')->save($this->className, $result);
}
$result = \ProcessPageViewStat\auto_download('https://download.ip2location.com/lite/IP2LOCATION-LITE-DB1.IPV6.BIN.ZIP', __DIR__.'/iploc/', 'IP2LOCATION-LITE-DB1.IPV6.BIN.ZIP');
if ($this->enable_logging == 1) {
wire('log')->save($this->className, $result);
}
}
/**
* Automatically updates the cache
*/
public function ProcessPageViewCacheUpdate(HookEvent $event) {
$this->update_cache();
}
/**
* Stores the record in the database
*/
private function add_record($performance, $vt, $usr, $ip_addr, $country_name, $country_image, $browser_name, $browser_image, $os_name, $os_image, $request, $origin) {
$query = $this->database->prepare("INSERT INTO ".self::dbTableIp." (ip) VALUES (:ip) ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id)");
$query->bindValue(':ip', $ip_addr, \PDO::PARAM_STR);
if (!$query->execute()) {
if ($this->enable_logging == 1) {
wire('log')->save($this->className, 'INSERT '.self::dbTableIp.' '.$query->errorCode().' '.print_r($query->errorInfo(), true));
}
return;
}
$id_ip = $this->database->lastInsertId();
if ($id_ip == 0) {
if ($this->enable_logging == 1) {
wire('log')->save($this->className, 'id_ip 0');
}
return;
}
$query = $this->database->prepare("INSERT INTO ".self::dbTableCountry." (country,countryimg) VALUES (:country_name,:country_image) ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id)");
$query->bindValue(':country_name', $country_name, \PDO::PARAM_STR);
$query->bindValue(':country_image', $country_image, \PDO::PARAM_STR);
if (!$query->execute()) {
if ($this->enable_logging == 1) {
wire('log')->save($this->className, 'INSERT '.self::dbTableCountry.' '.$query->errorCode().' '.print_r($query->errorInfo(), true));
}
return;
}
$id_country = $this->database->lastInsertId();
if ($id_country == 0) {
if ($this->enable_logging == 1) {
wire('log')->save($this->className, 'id_country 0');
}
return;
}
$query = $this->database->prepare("INSERT INTO ".self::dbTableBrowser." (browser,browserimg) VALUES (:browser_name,:browser_image) ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id)");
$query->bindValue(':browser_name', $browser_name, \PDO::PARAM_STR);
$query->bindValue(':browser_image', $browser_image, \PDO::PARAM_STR);
if (!$query->execute()) {
if ($this->enable_logging == 1) {
wire('log')->save($this->className, 'INSERT '.self::dbTableBrowser.' '.$query->errorCode().' '.print_r($query->errorInfo(), true));
}
return;
}
$id_browser = $this->database->lastInsertId();
if ($id_browser == 0) {
if ($this->enable_logging == 1) {
wire('log')->save($this->className, 'id_browser 0');
}
return;
}
$query = $this->database->prepare("INSERT INTO ".self::dbTableOs." (os,osimg) VALUES (:os_name,:os_image) ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id)");
$query->bindValue(':os_name', $os_name, \PDO::PARAM_STR);
$query->bindValue(':os_image', $os_image, \PDO::PARAM_STR);
if (!$query->execute()) {
if ($this->enable_logging == 1) {
wire('log')->save($this->className, 'INSERT '.self::dbTableOs.' '.$query->errorCode().' '.print_r($query->errorInfo(), true));
}
return;
}
$id_os = $this->database->lastInsertId();
if ($id_os == 0) {
if ($this->enable_logging == 1) {
wire('log')->save($this->className, 'id_os 0');
}
return;
}
$query = $this->database->prepare("INSERT INTO ".self::dbTablePage." (page) VALUES (:request) ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id)");
$query->bindValue(':request', $request, \PDO::PARAM_STR);
if (!$query->execute()) {
if ($this->enable_logging == 1) {
wire('log')->save($this->className, 'INSERT '.self::dbTablePage.' '.$query->errorCode().' '.print_r($query->errorInfo(), true));
}
return;
}
$id_request = $this->database->lastInsertId();
if ($id_request == 0) {
if ($this->enable_logging == 1) {
wire('log')->save($this->className, 'id_request 0');
}
return;
}
$query = $this->database->prepare("INSERT INTO ".self::dbTableOrigin." (origin) VALUES (:origin) ON DUPLICATE KEY UPDATE id = LAST_INSERT_ID(id)");
$query->bindValue(':origin', $origin, \PDO::PARAM_STR);
if (!$query->execute()) {
if ($this->enable_logging == 1) {
wire('log')->save($this->className, 'INSERT '.self::dbTableOrigin.' '.$query->errorCode().' '.print_r($query->errorInfo(), true));
}
return;
}
$id_origin = $this->database->lastInsertId();
if ($id_origin == 0) {
if ($this->enable_logging == 1) {
wire('log')->save($this->className, 'id_origin 0');
}
return;
}
$query = $this->database->prepare("INSERT INTO ".self::dbTableMain." (tm,performance,vt,usr,ip_id,country_id,browser_id,os_id,page_id,origin_id) VALUES (NOW(),:performance,:vt,:usr,:id_ip,:id_country,:id_browser,:id_os,:id_request,:id_origin)");
$query->bindValue(':performance', $performance, \PDO::PARAM_STR);
$query->bindValue(':vt', (int) $vt, \PDO::PARAM_INT);
$query->bindValue(':usr', (int) $usr, \PDO::PARAM_INT);
$query->bindValue(':id_ip', (int) $id_ip, \PDO::PARAM_INT);
$query->bindValue(':id_country', (int) $id_country, \PDO::PARAM_INT);
$query->bindValue(':id_browser', (int) $id_browser, \PDO::PARAM_INT);
$query->bindValue(':id_os', (int) $id_os, \PDO::PARAM_INT);
$query->bindValue(':id_request', (int) $id_request, \PDO::PARAM_INT);
$query->bindValue(':id_origin', (int) $id_origin, \PDO::PARAM_INT);
try {
if (!$query->execute()) {
if ($this->enable_logging == 1) {
wire('log')->save($this->className, 'INSERT '.self::dbTableMain.' '.$query->errorCode().' '.print_r($query->errorInfo(), true));
}
}
} catch (\Exception $e) {
if ($this->enable_logging == 1) {
wire('log')->save($this->className, 'Exception in add_record: '.$e);
}
}
}
/**
* Find out the IP address
*/
private function get_ip() {
$ip = $_SERVER['REMOTE_ADDR'];
if (!empty($ip)) {
return $ip;
} else {
$ip = getenv("REMOTE_ADDR");
if (!empty($ip)) {
return $ip;
} else {
return '0.0.0.0';
}
}
}
/**
* Prepares the data before being stored in the database
*/
private function prepare_record($vt, $request, $origin) {
if ($vt == 0) {
$performance = microtime(true) - $this->init_time;
} else {
$performance = 0;
}
$ip_addr = $this->get_ip();
$country_name = '';
$country_image = '';
require_once(__DIR__.'/func/IP2Location.php');
if (strpos($ip_addr, ':') !== false) {
if (file_exists(__DIR__.'/iploc/IP2LOCATION-LITE-DB1.IPV6.BIN')) {
$db = new \ProcessPageViewStat\Database(__DIR__.'/iploc/IP2LOCATION-LITE-DB1.IPV6.BIN', \ProcessPageViewStat\Database::FILE_IO);
$temp_records = $db->lookup($ip_addr, \ProcessPageViewStat\Database::ALL);
if (isset($temp_records['countryName'])) {
$country_name = $temp_records['countryName'];
}
if (isset($temp_records['countryCode'])) {
$country_image = strtolower($temp_records['countryCode']);
}
}
} else {
if (file_exists(__DIR__.'/iploc/IP2LOCATION-LITE-DB1.BIN')) {
$db = new \ProcessPageViewStat\Database(__DIR__.'/iploc/IP2LOCATION-LITE-DB1.BIN', \ProcessPageViewStat\Database::FILE_IO);
$temp_records = $db->lookup($ip_addr, \ProcessPageViewStat\Database::ALL);
if (isset($temp_records['countryName'])) {
$country_name = $temp_records['countryName'];
}
if (isset($temp_records['countryCode'])) {
$country_image = strtolower($temp_records['countryCode']);
}
}
}
if (($country_name == '') || ($country_name == '-')) $country_name = 'Unknown';
if (($country_image == '') || ($country_image == '-')) $country_image = 'unknown';
require_once(__DIR__.'/func/images.php');
require_once(__DIR__.'/func/UserAgentParser.php');
$browser_name = '';
$browser_image = '';
$platform = '';
$platform_image = '';
$useragent = \ProcessPageViewStat\parse_user_agent($_SERVER['HTTP_USER_AGENT']);
if ((isset($useragent['browser'])) && ($useragent['browser'] != null)) {
$browser_name = $useragent['browser'];
}
$browser_image = \ProcessPageViewStat\get_browser_img(strtolower($browser_name));
if ((isset($useragent['platform'])) && ($useragent['platform'] != null)) {
$platform = $useragent['platform'];
}
$platform_image = \ProcessPageViewStat\get_platform_img(strtolower($platform));
if ($this->record_user == '1') {
$usr = wire('user')->id;
} else {
$usr = 0;
}
$this->add_record($performance, $vt, $usr, $ip_addr, $country_name, $country_image, $browser_name, $browser_image, $platform, $platform_image, $request, $origin);
}
/**
* Receives the time of view
*/
public function ProcessPageViewReceiver(HookEvent $event) {
if ($event->arguments[1] == '/vts/') {
$vt = intval($this->input->get('t', 'int', 0));
if ($vt <= 0) exit(0);
$request = $this->input->get('u', 'text');
if (is_array($request)) {
if ($this->enable_logging == 1) {
wire('log')->save($this->className, 'Input is array '.$this->get_ip());
}
exit(0);
}
if (stripos(' '.$request, 'https://'.$_SERVER['SERVER_NAME']) == 1) {
$request = substr($request, strlen('https://'.$_SERVER['SERVER_NAME']));
}
if (stripos(' '.$request, 'http://'.$_SERVER['SERVER_NAME']) == 1) {
$request = substr($request, strlen('http://'.$_SERVER['SERVER_NAME']));
}
$request = substr($request, 0, 255);
$origin = $this->input->get('r', 'text');
if (is_array($origin)) {
if ($this->enable_logging == 1) {
wire('log')->save($this->className, 'Input is array '.$this->get_ip());
}
exit(0);
}
if (stripos(' '.$origin, 'https://'.$_SERVER['SERVER_NAME']) == 1) {
$origin = substr($origin, strlen('https://'.$_SERVER['SERVER_NAME']));
}
if (stripos(' '.$origin, 'http://'.$_SERVER['SERVER_NAME']) == 1) {
$origin = substr($origin, strlen('http://'.$_SERVER['SERVER_NAME']));
}
$origin = substr($origin, 0, 255);
$this->prepare_record($vt, $request, $origin);
exit(0);
}
}
/**
* Records the page view
*/
public function ProcessPageViewHook(HookEvent $event) {
$page = $event->object;
if ($this->record_hidden != '1') {
if ($page->isHidden()) return;
}
if ($this->record_admin != '1') {
if ($page->template == 'admin') return;
}
if ($this->record_loggedin != '1') {
if (wire('user')->isLoggedin()) return;
}
if ($this->record_404 != '1') {
if (strpos($page->url, '/http404/') !== false) return;
}
if ($this->record_time == '1') {
$buffer = $event->return;
require_once(__DIR__.'/func/javascript.php');
$buffer = str_replace('<body>', '<body><script>'.\ProcessPageViewStat\get_javascript().'</script>', $buffer);
$event->return = $buffer;
}
$request = $this->wire('sanitizer')->entities($_SERVER['REQUEST_URI']);
$request = substr($request, 0, 255);
if (isset($_SERVER['HTTP_REFERER'])) {
$origin = $this->wire('sanitizer')->entities($_SERVER['HTTP_REFERER']);
if (stripos(' '.$origin, 'https://'.$_SERVER['SERVER_NAME']) == 1) {
$origin = substr($origin, strlen('https://'.$_SERVER['SERVER_NAME']));
}
if (stripos(' '.$origin, 'http://'.$_SERVER['SERVER_NAME']) == 1) {
$origin = substr($origin, strlen('http://'.$_SERVER['SERVER_NAME']));
}
$origin = substr($origin, 0, 255);
} else {
$origin = '';
}
$this->prepare_record(0, $request, $origin);
}
/**
* Shows the records
*/
public function ___execute() {
if ((isset($_GET['download'])) && ($_GET['download'] == 'csv')) {
if (isset($_GET['view'])) {
$view = $_GET['view'];
} else {
$view = self::ViewDetailedRecords;
}
if (isset($_GET['from'])) {
$utcfrom = $_GET['from'];
} else {
$utcfrom = 0;
}
if (isset($_GET['to'])) {
$utcto = $_GET['to'];
} else {
$utcto = 0;
}
$datetime = new \DateTime();
$datetime->setTimezone(new \DateTimeZone($this->time_zone));
$datetime->setTimestamp($utcfrom);
$file_name = $datetime->format('Y-m-d');
$file_name .= '-';
$datetime->setTimestamp($utcto);
$file_name .= $datetime->format('Y-m-d');
$file_name .= '.csv';
ob_clean();
header('HTTP/1.1 200 OK');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="'.$file_name.'"');
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Accept-Ranges: none');
echo '"sep=,"'."\r\n"; // to make Excel happy
switch ($view) {
case self::ViewDetailedRecords:
$this->renderDetailedExportCsv($utcfrom, $utcto);
break;
case self::ViewDaysOfMonth:
case self::ViewLast30Days:
case self::ViewLast60Days:
case self::ViewLast90Days:
case self::ViewLast180Days:
case self::ViewLast365Days:
case self::ViewAllDays:
$this->renderCachedDaysExportCsv($utcfrom, $utcto, $view);
break;
case self::ViewMonthsOfYear:
case self::ViewLast12Months:
case self::ViewAllMonths:
$this->renderCachedMonthsExportCsv($utcfrom, $utcto, $view);
break;
case self::ViewAllYears:
$this->renderCachedYearsExportCsv($utcfrom, $utcto);
break;
}
exit(0);
}
if (isset($_GET['whois'])) {
ob_clean();
require_once(__DIR__.'/func/ipinfo.php');
\ProcessPageViewStat\showIPInfo($_GET['whois'], $this->config()->urls->siteModules.$this->className, $this->show_map);
exit(0);
}
$start = $this->input->post('start', 'int', 0);
if (!isset($start)) $start = 0;
if ($start < 0) $start = 0;
$year = $this->input->post('year', 'int', 0);
if (!isset($year)) $year = 0;
$month = $this->input->post('month', 'int', 0);
if (!isset($month)) $month = 0;
$day = $this->input->post('day', 'int', 0);
if (!isset($day)) $day = 0;
$view = $this->input->post('view', 'int', self::ViewDetailedRecords);
if (!isset($view)) $view = self::ViewDetailedRecords;
if ($view < self::ViewDetailedRecords) $view = self::ViewDetailedRecords;
if ($view > self::ViewAllYears) $view = self::ViewAllYears;
if (($view == self::ViewDetailedRecords) ||
($view == self::ViewDaysOfMonth) ||
($view == self::ViewMonthsOfYear)) {
$s = sprintf('%04d-%02d-%02d', $year, $month, $day);
$d = \DateTime::createFromFormat('Y-m-d', $s);
if ($d && $d->format('Y-m-d') == $s) {
$date = new \DateTime($d->format('Y-m-d'), new \DateTimeZone($this->time_zone));
$date->setTime(0, 0, 0);
} else {
$date = new \DateTime('now', new \DateTimeZone($this->time_zone));
$date->setTime(0, 0, 0);
$s = $date->format('Y-m-d');
$month = date('m', strtotime($s));
$year = date('Y', strtotime($s));
$day = date('d', strtotime($s));
$date = new \DateTime($s, new \DateTimeZone($this->time_zone));
}
} else {
$date = new \DateTime('now', new \DateTimeZone($this->time_zone));
$date->setTime(0, 0, 0);
}
// begin filter
$result = '<form method="POST" id="pvs_filter" autocomplete="off">';
// view mode
$view_text = array(__('Detailed records'), __('Days of month'), __('Last 30 days'), __('Last 60 days'),
__('Last 90 days'), __('Last 180 days'), __('Last 365 days'), __('All days'), __('Months of year'), __('Last 12 months'), __('All months'), __('All years'), 'Days', 'Months', 'Years');
$result .= '<select name="view" onchange="this.form.submit();" autocomplete="off">';
for ($i = self::ViewDetailedRecords; $i <= self::ViewAllYears; $i++) {
$result .= '<option value="'.$i.'"';
if ($i == $view) $result .= ' selected="selected"';
$result .= '>'.$view_text[$i].'</option>';
}
$result .= '</select>';
// day
$result .= '<select name="day" id="day"';
if ($view <> self::ViewDetailedRecords) {
$result .= ' style="display:none"';
}
$result .= ' onchange="this.form.submit();" autocomplete="off">';
$daysofmonth = cal_days_in_month(CAL_GREGORIAN, $month, $year);
for ($i = 1; $i <= $daysofmonth; $i++) {
$result .= '<option value="'.$i.'"';
if ($i == $day) $result .= ' selected="selected"';
$result .= '>'.$i.'</option>';
}
$result .= '</select>';
// month
$result .= '<select name="month" id="month"';
if (($view <> self::ViewDetailedRecords) && ($view <> self::ViewDaysOfMonth)) {
$result .= ' style="display:none"';
}
$result .= ' onchange="this.form.submit();" autocomplete="off">';
for ($i = 1; $i <= 12; $i++) {
$result .= '<option value="'.$i.'"';
if ($i == $month) $result .= ' selected="selected"';
$month_name = \DateTime::createFromFormat('!m', $i);
$result .= '>'.$month_name->format('F').'</option>';
}
$result .= '</select>';
// year
$result .= '<select name="year" id="year"';
if (($view <> self::ViewDetailedRecords) && ($view <> self::ViewDaysOfMonth) && ($view <> self::ViewMonthsOfYear)) {
$result .= ' style="display:none"';
}
$result .= ' onchange="this.form.submit();" autocomplete="off">';
$years = new \DateTime('now', new \DateTimeZone($this->time_zone));
$startyear = $years->format('Y') - 20;
$endyear = $years->format('Y');
for ($i = $startyear; $i <= $endyear; $i++) {
$result .= '<option value="'.$i.'"';
if ($i == $year) $result .= ' selected="selected"';
$result .= '>'.$i.'</option>';
}
$result .= '</select>';
// update
$result .= '<button title="'.__('Update').'" id="pvs_update" onclick="this.form.submit();"> </button>';
$result .= '</form>';
// end filter
if ($view <> self::ViewDetailedRecords) {
if ($this->cache_update_interval == '') {
$this->update_cache();
}
}
$this->config()->scripts->add($this->config()->urls->siteModules.$this->className.'/dragscroll.js');
$this->config()->styles->add($this->config()->urls->siteModules.$this->className.'/pvs.css?v=1.2.1');
switch ($view) {
case self::ViewDetailedRecords:
$utcfrom = $date->format('U');
$date->modify('+1 day');
$utcto = $date->format('U');
$result .= $this->renderDetailedRecords($utcfrom, $utcto, $start);
break;
case self::ViewDaysOfMonth:
$date->modify('first day of this month 00:00:00');
$utcfrom = $date->format('U');
$date->modify('+1 month');
$utcto = $date->format('U');
$result .= $this->renderCachedVisitorCountsDays($utcfrom, $utcto, $view, $start);
break;
case self::ViewLast30Days:
$datefrom = clone $date;
$dateto = clone $date;
$datefrom->modify('29 days ago');
$utcfrom = $datefrom->format('U');
$dateto->modify('+1 day');
$utcto = $dateto->format('U');
$result .= $this->renderCachedVisitorCountsDays($utcfrom, $utcto, $view, $start);
break;
case self::ViewLast60Days:
$datefrom = clone $date;
$dateto = clone $date;
$datefrom->modify('59 days ago');
$utcfrom = $datefrom->format('U');
$dateto->modify('+1 day');
$utcto = $dateto->format('U');
$result .= $this->renderCachedVisitorCountsDays($utcfrom, $utcto, $view, $start);
break;
case self::ViewLast90Days:
$datefrom = clone $date;
$dateto = clone $date;
$datefrom->modify('89 days ago');
$utcfrom = $datefrom->format('U');
$dateto->modify('+1 day');
$utcto = $dateto->format('U');
$result .= $this->renderCachedVisitorCountsDays($utcfrom, $utcto, $view, $start);
break;
case self::ViewLast180Days:
$datefrom = clone $date;
$dateto = clone $date;
$datefrom->modify('179 days ago');
$utcfrom = $datefrom->format('U');
$dateto->modify('+1 day');
$utcto = $dateto->format('U');
$result .= $this->renderCachedVisitorCountsDays($utcfrom, $utcto, $view, $start);
break;
case self::ViewLast365Days:
$datefrom = clone $date;
$dateto = clone $date;
$datefrom->modify('364 days ago');
$utcfrom = $datefrom->format('U');
$dateto->modify('+1 day');
$utcto = $dateto->format('U');
$result .= $this->renderCachedVisitorCountsDays($utcfrom, $utcto, $view, $start);
break;
case self::ViewAllDays:
$utcfrom = 0;
$date->modify('+1 day');
$utcto = $date->format('U');
$result .= $this->renderCachedVisitorCountsDays($utcfrom, $utcto, $view, $start);
break;
case self::ViewMonthsOfYear:
$date->modify('first day of January this year 00:00:00');
$utcfrom = $date->format('U');
$date->modify('+1 year');
$utcto = $date->format('U');
$result .= $this->renderCachedVisitorCountsMonths($utcfrom, $utcto, $view, $start);
break;
case self::ViewLast12Months:
$datefrom = clone $date;
$dateto = clone $date;
$datefrom->modify('first day of this month 00:00:00');
$datefrom->modify('11 months ago');
$utcfrom = $datefrom->format('U');
$dateto->modify('+1 day');
$utcto = $dateto->format('U');
$result .= $this->renderCachedVisitorCountsMonths($utcfrom, $utcto, $view, $start);
break;
case self::ViewAllMonths:
$utcfrom = 0;
$date->modify('+1 day');
$utcto = $date->format('U');
$result .= $this->renderCachedVisitorCountsMonths($utcfrom, $utcto, $view, $start);
break;
case self::ViewAllYears:
$utcfrom = 0;
$date->modify('+1 day');
$utcto = $date->format('U');
$result .= $this->renderCachedVisitorCountsYears($utcfrom, $utcto, $view, $start);
break;
}
$result .= '<div class="pvs_config">';
$result .= '<a class="InputfieldButtonLink" href="'."{$this->config->urls->admin}module/edit?name={$this->className}".'" tabindex="-1"><button id="moduleConfigLink" class="ui-button ui-widget ui-state-default ui-corner-all" name="button" value="'.__('Configuration').'" type="button"><span class="ui-button-text"><i class="fa fa-cog"></i> '.__('Configuration').'</span></button></a>';
$result .= ' <a class="InputfieldButtonLink" href="?download=csv&view='.$view.'&from='.$utcfrom.'&to='.$utcto.'" target="_blank"><button id="moduleConfigLink" class="ui-button ui-widget ui-state-default ui-corner-all" name="button" value="'.__('CSV').'" type="button"><span class="ui-button-text"><i class="fa fa-download"></i> '.__('CSV').'</span></button></a>';
$result .= '</div>';
return $result;
}
/**
* Prepares the output of cached visitor counts by year
*/
private function renderCachedVisitorCountsYears($utcfrom, $utcto, $view, $start) {
$this->database->query('CREATE TABLE IF NOT EXISTS '.self::dbTableCache.' ('.
'id int(10) unsigned NOT NULL AUTO_INCREMENT,'.
'tm timestamp NOT NULL,'.
'counts int(10) unsigned,'.
'PRIMARY KEY(id),'.
'UNIQUE INDEX(tm)'.
') ENGINE='.$this->wire('config')->dbEngine.' DEFAULT CHARSET='.$this->wire('config')->dbCharset.';');
$sql = "SELECT SQL_CALC_FOUND_ROWS UNIX_TIMESTAMP(tm), YEAR(tm) as yr, SUM(counts) AS totalcount FROM ".self::dbTableCache." WHERE tm >= FROM_UNIXTIME(:utcfrom) AND tm < FROM_UNIXTIME(:utcto) GROUP BY yr ORDER BY tm ASC LIMIT :start,:rowlimit";
$query = $this->database->prepare($sql);
$query->bindValue(':utcfrom', (int) $utcfrom, \PDO::PARAM_INT);
$query->bindValue(':utcto', (int) $utcto, \PDO::PARAM_INT);
$query->bindValue(':start', (int) $start, \PDO::PARAM_INT);
$query->bindValue(':rowlimit', (int) $this->row_limit, \PDO::PARAM_INT);
if (!$query->execute()) {
return 'Error: '.$query->errorCode().' '.print_r($query->errorInfo(), true);
}
$temp1 = $this->database->query("SELECT FOUND_ROWS()");
$temp2 = $temp1->fetch();
if (is_numeric($temp2[0])) {
$rows = $temp2[0];
} else {
$rows = 0;
}
$records = $query->fetchAll(\PDO::FETCH_ASSOC);
$max = 0;
foreach ($records as $record) {
if ($max < $record['totalcount']) $max = $record['totalcount'];
}
$result = '';
if ($this->row_limit < $rows) {
$result .= '<form method="POST" class="pvs_pagination" autocomplete="off">';
$result .= '<input type="hidden" name="day" id="day1" value="">';
$result .= '<input type="hidden" name="month" id="month1" value="">';
$result .= '<input type="hidden" name="year" id="year1" value="">';
$result .= '<input type="hidden" name="view" value="'.$view.'">';
$result .= '<select name="start" id="id_pageselect1" onchange="this.form.submit();"></select>';
$result .= '</form>';
$result .= '<div class="pvs_clear"></div>';
}
$result .= '<div class="dragscroll">';
$result .= '<div class="pvs_table">';
$result .= '<div class="pvs_thead">';
$result .= '<div class="pvs_th pvs_alr">'.__('Year').'</div>';
$result .= '<div class="pvs_th pvs_alr">'.__('Visitors').'</div>';
$result .= '<div class="pvs_th">'.__('Chart').'</div>';
$result .= '</div>';
$datetime = new \DateTime();
$datetime->setTimezone(new \DateTimeZone('UTC'));
$lnmode = ' pvs_ln';
foreach ($records as $record) {
$datetime->setTimestamp($record['UNIX_TIMESTAMP(tm)']);
if ($lnmode == '') {
$lnmode = ' pvs_ln';
} else {
$lnmode = '';
}
$result .= '<div class="pvs_tr">';
$result .= '<div class="pvs_td pvs_alr'.$lnmode.'">'.$datetime->format('Y').'</div>';
$result .= '<div class="pvs_td pvs_alr'.$lnmode.'">'.$record['totalcount'].'</div>';
if ($max > 0) {
$chart = round(($record['totalcount'] / $max) * self::ChartMaxSize);
} else {
$chart = 0;
}
$result .= '<div class="pvs_td pvs_w100'.$lnmode.'">';
$result .= '<div class="pvs_chart">';
$result .= '<div class="pvs_chart_gauge" style="width:'.$chart.'px;"></div>';
$result .= '</div>';
$result .= '</div>';
$result .= '</div>';
}
$result .= '</div>';
$result .= '</div>';
if ($this->row_limit < $rows) {
$result .= '<form method="POST" class="pvs_pagination" autocomplete="off">';
$result .= '<input type="hidden" name="day" id="day2" value="">';
$result .= '<input type="hidden" name="month" id="month2" value="">';
$result .= '<input type="hidden" name="year" id="year2" value="">';
$result .= '<input type="hidden" name="view" value="'.$view.'">';
$result .= '<select name="start" id="id_pageselect2" onchange="this.form.submit();"></select>';
$result .= '</form>';
$result .= '<div class="pvs_clear"></div>';
$result .= '<script>';
$result .= 'document.getElementById("day1").value = document.getElementById("day").value;';