-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathwp-slimstat.php
More file actions
1631 lines (1376 loc) · 70.2 KB
/
wp-slimstat.php
File metadata and controls
1631 lines (1376 loc) · 70.2 KB
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
/*
* Plugin Name: SlimStat Analytics
* Plugin URI: https://wp-slimstat.com/
* Description: The leading web analytics plugin for WordPress
* Version: 5.4.2
* Author: Jason Crouse, VeronaLabs
* Text Domain: wp-slimstat
* Domain Path: /languages
* Author URI: https://wp-slimstat.com/
* License: GPL-2.0+
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Requires at least: 5.6
* Requires PHP: 7.4
*/
// check if composer autoloader exists
if (!file_exists(__DIR__ . '/vendor/autoload.php')) {
return;
}
// Set the plugin version and directory
define('SLIMSTAT_ANALYTICS_VERSION', '5.4.2');
define('SLIMSTAT_FILE', __FILE__);
define('SLIMSTAT_DIR', __DIR__);
define('SLIMSTAT_URL', plugins_url('', __FILE__));
// include the autoloader if it exists
require_once __DIR__ . '/vendor/autoload.php';
// Include Constants.php to make SLIMSTAT_ANALYTICS_DIR available to traits
require_once __DIR__ . '/src/Constants.php';
/**
* Main Slimstat Analytics Class
*
* @package Wp_SlimStat
*
* @todo REFACTOR TRACKING STATE: The $data_js and $stat properties should be refactored into a
* proper state object pattern to maintain encapsulation. Currently these properties are
* public to support refactored tracker classes (SlimStat\Tracker\*), but this breaks
* encapsulation and creates security risks. Future implementation should:
* 1. Create a TrackingState class to encapsulate state management
* 2. Update all Tracker classes to use the state object
* 3. Make properties protected or private
* 4. Ensure all state modifications go through validated methods
* This is tracked as technical debt for version 6.0
*/
// Include Constants.php to make SLIMSTAT_ANALYTICS_DIR available to traits
require_once __DIR__ . '/src/Constants.php';
class wp_slimstat
{
public static $settings = [];
public static $wpdb;
public static $upload_dir = '';
public static $update_checker = [];
public static $raw_post_array = [];
/**
* @var array Tracking data from JavaScript (for internal tracking use only)
* @internal Use get_data_js() / set_data_js() methods for controlled access.
*
* This property is now protected to maintain proper encapsulation and prevent external code
* from bypassing consent checks or corrupting tracking state. All tracker classes use the
* getter/setter methods which include validation and filter hooks for GDPR compliance.
*/
protected static $data_js = ['id' => 0];
/**
* @var array Current pageview tracking data (for internal tracking use only)
* @internal Use get_stat() / set_stat() methods for controlled access.
*
* This property is now protected to maintain proper encapsulation and prevent external code
* from bypassing consent checks or corrupting tracking state. All tracker classes use the
* getter/setter methods which include validation and filter hooks for GDPR compliance.
*/
protected static $stat = [];
protected static $date_i18n_filters = [];
/**
* Gets the current data_js array (for internal tracking use only)
*
* @return array
*/
public static function get_data_js()
{
return self::$data_js;
}
/**
* Sets the data_js array (for internal tracking use only)
*
* This method provides controlled access to the data_js property and includes
* basic validation to prevent tampering.
*
* @param array $data_js The tracking data from JavaScript
* @return void
* @internal For use by SlimStat tracking classes only
*/
public static function set_data_js($data_js)
{
// Validate that we're receiving an array
if (!is_array($data_js)) {
return;
}
// Apply filter to allow validation/modification by consent management systems
$data_js = apply_filters('slimstat_set_data_js', $data_js);
self::$data_js = $data_js;
}
/**
* Gets the current stat array (for internal tracking use only)
*
* @return array Current tracking state
* @internal For use by SlimStat tracking classes only
*/
public static function get_stat()
{
return self::$stat;
}
/**
* Sets the stat array (for internal tracking use only)
*
* This method provides controlled access to the stat property and includes
* basic validation to prevent tampering and ensure consent compliance.
*
* @param array $stat The pageview tracking data
* @return void
* @internal For use by SlimStat tracking classes only
*/
public static function set_stat($stat)
{
// Validate that we're receiving an array
if (!is_array($stat)) {
return;
}
// Apply filter to allow validation/modification by consent management systems
// This is critical for GDPR compliance - CMPs can inspect and modify data
$stat = apply_filters('slimstat_set_stat', $stat);
self::$stat = $stat;
}
/**
* Initializes variables and actions
*/
public static function init()
{
\SlimStat\Providers\RestApiManager::run();
// Load all the settings
if (is_network_admin() && (empty($_GET['page']) || false === strpos($_GET['page'], 'slimview'))) {
self::$settings = get_site_option('slimstat_options', []);
} else {
self::$settings = get_option('slimstat_options', []);
}
if (empty(self::$settings)) {
// Fresh install: set defaults including geolocation_provider=dbip
self::$settings = self::get_fresh_defaults();
self::update_option('slimstat_options', self::$settings);
}
self::$settings = array_merge(self::init_options(), self::$settings);
// Allow third party tools to edit the options
self::$settings = apply_filters('slimstat_init_options', self::$settings);
$consent_integration = self::$settings['consent_integration'] ?? '';
// If WP Consent API is selected but the function doesn't exist, reset to default
if ('wp_consent_api' === $consent_integration && !function_exists('wp_has_consent')) {
$consent_integration = '';
self::$settings['consent_integration'] = '';
}
if ('' === $consent_integration && ('on' === (self::$settings['use_slimstat_banner'] ?? 'off'))) {
$consent_integration = 'slimstat_banner';
self::$settings['consent_integration'] = $consent_integration;
}
if ('slimstat_banner' === $consent_integration) {
self::$settings['use_slimstat_banner'] = 'on';
} else {
self::$settings['use_slimstat_banner'] = 'off';
}
// Allow third-party tools to use a custom database for Slimstat
self::$wpdb = apply_filters('slimstat_custom_wpdb', $GLOBALS['wpdb']);
// Define the folder where to store the geolocation database (shared among sites in a network, by default)
if (defined('UPLOADS')) {
self::$upload_dir = ABSPATH . UPLOADS . '/wp-slimstat';
} else {
$upload_dir_info = wp_upload_dir();
self::$upload_dir = $upload_dir_info['basedir'];
// Handle multisite environment
if (is_multisite() && !(is_main_network() && is_main_site() && defined('MULTISITE'))) {
self::$upload_dir = str_replace('/sites/' . get_current_blog_id(), '', self::$upload_dir);
}
self::$upload_dir .= '/wp-slimstat';
}
// Apply filter to allow customization of the upload directory
self::$upload_dir = apply_filters('slimstat_maxmind_path', self::$upload_dir);
// Allow add-ons to turn off the tracker based on other conditions
$is_tracking_filter = apply_filters('slimstat_filter_pre_tracking', false === strpos(self::get_request_uri(), 'wp-admin/admin-ajax.php'));
$is_tracking_filter_js = apply_filters('slimstat_filter_pre_tracking_js', true);
// Enable the tracker (both server- and client-side)
if ((!is_admin() || 'on' == self::$settings['track_admin_pages']) && 'on' == self::$settings['is_tracking'] && $is_tracking_filter) {
// Is server-side tracking active?
if ('on' != self::$settings['javascript_mode']) {
add_action(is_admin() ? 'admin_init' : 'wp', [\SlimStat\Tracker\Tracker::class, 'slimtrack'], 5);
if ('on' != self::$settings['ignore_wp_users']) {
add_action('login_init', [\SlimStat\Tracker\Tracker::class, 'slimtrack'], 10);
}
}
// Slimstat tracks screen resolutions, outbound links and other client-side information using a client-side tracker
add_action(is_admin() ? 'admin_enqueue_scripts' : 'wp_enqueue_scripts', [self::class, 'enqueue_tracker'], 15);
if ('on' != self::$settings['ignore_wp_users']) {
add_action('login_enqueue_scripts', [self::class, 'enqueue_tracker'], 10);
}
add_filter('script_loader_tag', [self::class, 'add_defer_to_script_tag'], 10, 2);
}
$banner_enabled = ('on' === (self::$settings['gdpr_enabled'] ?? 'on'))
&& ('on' === (self::$settings['use_slimstat_banner'] ?? 'off'));
if ($banner_enabled) {
add_action('wp_enqueue_scripts', [self::class, 'enqueue_gdpr_assets'], 20);
add_action('login_enqueue_scripts', [self::class, 'enqueue_gdpr_assets'], 20);
add_action('wp_footer', [self::class, 'render_gdpr_banner'], 5);
add_action('login_footer', [self::class, 'render_gdpr_banner'], 5);
}
// Registers Slimstat with WP Consent API if enabled in plugin settings
if ((self::$settings['consent_integration'] ?? '') === 'wp_consent_api') {
// Check if WP Consent API plugin is actually active
if (function_exists('wp_has_consent')) {
$plugin = plugin_basename(SLIMSTAT_FILE);
add_filter("wp_consent_api_registered_{$plugin}", '__return_true');
// Register cookie info with WP Consent API for CMP display
if (function_exists('wp_add_cookie_info')) {
wp_add_cookie_info(
'slimstat_tracking_code',
'SlimStat Analytics',
'statistics',
intval(self::$settings['session_duration'] ?? 1800) . ' ' . __('seconds', 'wp-slimstat'),
__('Session cookie that identifies returning visitors for analytics.', 'wp-slimstat'),
'',
false,
false
);
}
}
}
// Register WordPress Privacy API exporters and erasers (GDPR Article 15 & 17)
add_filter('wp_privacy_personal_data_exporters', [\SlimStat\Services\Privacy\DataExporter::class, 'registerExporters']);
add_filter('wp_privacy_personal_data_erasers', [\SlimStat\Services\Privacy\DataEraser::class, 'registerErasers']);
// Register privacy policy content
add_action('admin_init', [self::class, 'registerPrivacyPolicyContent']);
// Register AJAX handlers for consent upgrade/revocation (anonymous tracking mode)
\SlimStat\Services\Privacy\ConsentHandler::registerAjaxHandlers();
// Hook a DB clean-up routine to the daily cronjob
add_action('wp_slimstat_purge', [self::class, 'wp_slimstat_purge']);
// Hook IP hashing daily salt generation (for GDPR compliance)
add_action('wp_slimstat_generate_daily_salt', [\SlimStat\Providers\IPHashProvider::class, 'generateDailySalt']);
// Hook a GeoIP database update routine to the daily cronjob
add_action('wp_slimstat_update_geoip_database', [self::class, 'wp_slimstat_update_geoip_database']);
// Allow external domains on CORS requests
add_filter('allowed_http_origins', [self::class, 'open_cors_admin_ajax']);
// Internal GDPR banner/consent handling removed. Use external CMP plugins.
// If this request was a redirect, we should update the content type accordingly
add_filter('wp_redirect_status', [\SlimStat\Tracker\Tracker::class, 'update_content_type'], 10, 2);
// Shortcodes
add_shortcode('slimstat', [self::class, 'slimstat_shortcode'], 15);
// Init the plugin functionality
add_action('init', [self::class, 'init_plugin']);
// REST API Support
add_action('rest_api_init', [self::class, 'register_rest_route']);
// Load the admin library
if (is_user_logged_in()) {
include_once(plugin_dir_path(__FILE__) . 'admin/index.php');
add_action('init', ['wp_slimstat_admin', 'init'], 60);
}
}
// end init
/**
* Load plugin textdomain
*
* @return void
*/
public static function load_textdomain()
{
load_plugin_textdomain('wp-slimstat', false, '/wp-slimstat/languages');
}
/**
* The main logging function
*
* @param string $message The message to be logged.
* @param string $level The log level (e.g., 'info', 'warning', 'error'). Default is 'info'.
*
* @uses error_log
*/
public static function log($message, $level = 'info')
{
if (is_array($message)) {
$message = wp_json_encode($message);
}
$log_level = strtoupper($level);
// Log when debug is enabled
if (defined('WP_DEBUG') && WP_DEBUG) {
error_log(sprintf('[WP SLIMSTAT] [%s]: %s', $log_level, $message));
}
}
/**
* Resolve the active geolocation provider.
*
* New UI sets 'geolocation_provider' explicitly (incl. 'disable').
* Legacy installs only have 'enable_maxmind' (tri-state: 'on', 'no', 'disable').
*
* @return string|false 'maxmind', 'dbip', 'cloudflare', or false if disabled
*/
public static function resolve_geolocation_provider()
{
if (isset(self::$settings['geolocation_provider'])) {
$p = sanitize_text_field(self::$settings['geolocation_provider']);
if ('disable' === $p) {
return false;
}
if (in_array($p, ['maxmind', 'dbip', 'cloudflare'], true)) {
return $p;
}
// Invalid/empty value — fall through to legacy flag
}
$em = self::$settings['enable_maxmind'] ?? 'disable';
if ('on' === $em) {
return 'maxmind';
}
if ('no' === $em) {
return 'dbip';
}
return false;
}
/**
* Decodes the permalink
*/
public static function get_request_uri()
{
$request_url = '';
if (isset($_SERVER['REQUEST_URI'])) {
return urldecode(sanitize_url(wp_unslash($_SERVER['REQUEST_URI'])));
} elseif (isset($_SERVER['SCRIPT_NAME'])) {
$request_url = sanitize_text_field(wp_unslash($_SERVER['SCRIPT_NAME']));
} elseif (isset($_SERVER['PHP_SELF'])) {
$request_url = sanitize_text_field(wp_unslash($_SERVER['PHP_SELF']));
}
if (isset($_SERVER['QUERY_STRING'])) {
$request_url .= '?' . sanitize_text_field(wp_unslash($_SERVER['QUERY_STRING']));
}
return $request_url;
}
// end get_request_uri
public static function is_local_ip_address($ip_address = '')
{
return !filter_var($ip_address, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE|FILTER_FLAG_NO_RES_RANGE);
}
/**
* Implements the Slimstat Shortcode API
*/
public static function slimstat_shortcode($_attributes = '', $_content = '')
{
shortcode_atts([
'f' => '', // recent, popular, count, widget
'w' => '', // column to use (for recent, popular and count) or widget to use
's' => ' ', // separator
'o' => 0, // offset for counters
], $_attributes);
$f = $_attributes['f'] ?? '';
$w = $_attributes['w'] ?? '';
$s = $_attributes['s'] ?? '';
$o = $_attributes['o'] ?? 0;
$output = '';
$where = '';
$as_column = '';
$s = sprintf("<span class='slimstat-item-separator'>%s</span>", $s);
// Look for required fields
if (empty($f) || empty($w)) {
return '<!-- Slimstat Shortcode Error: missing parameter -->';
}
// Validation the parameter w
if (false == in_array($w, ['count', 'display_name', 'hostname', 'post_link', 'post_link_no_qs', 'dt', 'username', 'post_link', 'ip', 'id', 'searchterms', 'username', 'resource', 'slim_p1_01', 'slim_p1_03', 'slim_p1_04', 'slim_p1_06', 'slim_p1_08', 'slim_p1_10', 'slim_p1_11', 'slim_p1_12', 'slim_p1_13', 'slim_p1_15', 'slim_p1_17', 'slim_p1_18', 'slim_p1_19_01', 'slim_p2_01', 'slim_p2_02', 'slim_p2_03', 'slim_p2_04', 'slim_p2_05', 'slim_p2_06', 'slim_p2_07', 'slim_p2_08', 'slim_p2_12', 'slim_p2_13', 'slim_p2_14', 'slim_p2_15', 'slim_p2_16', 'slim_p2_17', 'slim_p2_18', 'slim_p2_19', 'slim_p2_20', 'slim_p2_21', 'slim_p2_22_01', 'slim_p2_24', 'slim_p2_25', 'slim_p3_01', 'slim_p3_02', 'slim_p4_01', 'slim_p4_02', 'slim_p4_04', 'slim_p4_05', 'slim_p4_06', 'slim_p4_07', 'slim_p4_09', 'slim_p4_10', 'slim_p4_11', 'slim_p4_12', 'slim_p4_13', 'slim_p4_15', 'slim_p4_16', 'slim_p4_18', 'slim_p4_19', 'slim_p4_20', 'slim_p4_21', 'slim_p4_22', 'slim_p4_23', 'slim_p4_24', 'slim_p4_25', 'slim_p4_26_01', 'slim_p4_27', 'slim_p6_01', 'slim_p2_23'])) {
return '<!-- Slimstat Shortcode Error: invalid parameter for w -->';
}
// Include the Reports Library, but don't initialize the database, since we will do that separately later
include_once(plugin_dir_path(__FILE__) . 'admin/view/wp-slimstat-reports.php');
wp_slimstat_reports::init();
/**
* @SecurityProfile https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-0630
* Disabled because of the report from WP Scan
*/
// Init the database library with the appropriate filters
/*if ( strpos ( $_content, 'WHERE:' ) !== false ) {
$where = html_entity_decode( str_replace( 'WHERE:', '', $_content ), ENT_QUOTES, 'UTF-8' );
}
else{*/
wp_slimstat_db::init(html_entity_decode($_content, ENT_QUOTES, 'UTF-8'));
//}
switch ($f) {
case 'count':
case 'count-all':
$output = wp_slimstat_db::count_records($w, $where, false === strpos($f, 'all')) + $o;
break;
case 'widget':
if (empty(wp_slimstat_reports::$reports[$w])) {
return __('Invalid Report ID', 'wp-slimstat');
}
wp_register_style('wp-slimstat-frontend', plugins_url('/admin/assets/css/slimstat.css', __FILE__), true, SLIMSTAT_ANALYTICS_VERSION);
wp_enqueue_style('wp-slimstat-frontend');
wp_slimstat_reports::$reports[$w]['callback_args']['is_widget'] = true;
ob_start();
echo wp_slimstat_reports::report_header($w);
call_user_func(wp_slimstat_reports::$reports[$w]['callback'], wp_slimstat_reports::$reports[$w]['callback_args']);
wp_slimstat_reports::report_footer();
$output = ob_get_contents();
ob_end_clean();
break;
case 'recent':
case 'recent-all':
case 'top':
case 'top-all':
$function = 'get_' . str_replace('-all', '', $f);
if ('*' == $w) {
$w = 'id';
}
$w = esc_html($w);
$w = self::string_to_array($w);
// Some columns are 'special' and need be removed from the list
$w_clean = array_diff($w, ['count', 'display_name', 'hostname', 'post_link', 'post_link_no_qs', 'dt']);
// The special value 'display_name' requires the username to be retrieved
if (in_array('display_name', $w)) {
$w_clean[] = 'username';
}
// The special value 'post_list' requires the resource to be retrieved
if (in_array('post_link', $w)) {
$w_clean[] = 'resource';
}
// The special value 'post_list_no_qs' requires a substring to be calculated
if (in_array('post_link_no_qs', $w)) {
$w_clean = ['SUBSTRING_INDEX( resource, "' . (get_option('permalink_structure') ? '?' : '&') . '", 1 )'];
$as_column = 'resource';
}
// Retrieve the data
$results = wp_slimstat_db::$function(implode(', ', $w_clean), $where, '', false === strpos($f, 'all'), $as_column);
// No data? No problem!
if (empty($results)) {
return '<!-- Slimstat Shortcode: No Data -->';
}
// Are nice permalinks enabled?
$permalinks_enabled = get_option('permalink_structure');
// Format results
$output = [];
foreach ($results as $result_idx => $a_result) {
foreach ($w as $a_column) {
$output[$result_idx][$a_column] = sprintf("<span class='col-%s'>", $a_column);
switch ($a_column) {
case 'count':
$output[$result_idx][$a_column] .= $a_result['counthits'];
break;
case 'country':
$output[$result_idx][$a_column] .= wp_slimstat_i18n::get_string('c-' . $a_result[$a_column]);
break;
case 'display_name':
$user_details = get_user_by('login', $a_result['username']);
if (!empty($user_details)) {
$output[$result_idx][$a_column] .= $user_details->display_name;
} else {
$output[$result_idx][$a_column] .= $a_result['username'];
}
break;
case 'dt':
$output[$result_idx][$a_column] .= date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $a_result['dt']);
break;
case 'hostname':
$output[$result_idx][$a_column] .= self::gethostbyaddr($a_result['ip']);
break;
case 'language':
$output[$result_idx][$a_column] .= wp_slimstat_i18n::get_string('l-' . $a_result[$a_column]);
break;
case 'platform':
$output[$result_idx][$a_column] .= wp_slimstat_i18n::get_string($a_result[$a_column]);
break;
case 'post_link':
case 'post_link_no_qs':
$post_id = url_to_postid($a_result['resource']);
if ($post_id > 0) {
$output[$result_idx][$a_column] .= sprintf("<a href='%s'>", esc_url( $a_result[ 'resource' ] )) . esc_html( get_the_title($post_id) ) . '</a>';
} else {
$output[$result_idx][$a_column] .= sprintf("<a href='%s'>%s</a>", esc_url( $a_result[ 'resource' ] ), esc_html( $a_result[ 'resource' ] ));
}
break;
default:
$output[$result_idx][$a_column] .= $a_result[$a_column] ?? '';
break;
}
$output[$result_idx][$a_column] .= '</span>';
}
$output[$result_idx] = '<li>' . implode($s, $output[$result_idx]) . '</li>';
}
$output = '<ul class="slimstat-shortcode ' . $f . implode('-', $w) . '">' . implode('', $output) . '</ul>';
break;
default:
break;
}
return $output;
}
// end slimstat_shortcode
public static function init_plugin()
{
// Include our browser detector library
\SlimStat\Services\Browscap::init();
// Make sure the upload directory is exist and is protected.
self::create_upload_directory();
// Ensure daily salt exists for IP hashing (GDPR compliance)
// This runs on every page load but only generates if missing
\SlimStat\Providers\IPHashProvider::generateDailySalt();
// Initialize adblock bypass functionality
\SlimStat\Tracker\Tracker::rewrite_rule_tracker();
add_action('template_redirect', [\SlimStat\Tracker\Tracker::class, 'adblocker_javascript']);
add_action('init', [\SlimStat\Tracker\Tracker::class, 'rewrite_rule_tracker']);
}
/**
* Opens given domains during CORS requests to admin-ajax.php
*/
public static function open_cors_admin_ajax($_allowed_origins = [])
{
$exploded_domains = self::string_to_array(self::$settings['external_domains']);
if (!empty($exploded_domains) && !empty($exploded_domains[0])) {
$_allowed_origins = array_merge($_allowed_origins, $exploded_domains);
}
return $_allowed_origins;
}
// end open_cors_admin_ajax
/**
* Implements a REST API interface to retrieve Slimstat reports and metrics
*/
public static function rest_api_response($_request = [])
{
$filters = '';
if (!empty($_request['filters'])) {
$filters = $_request['filters'];
}
if (empty($_request['dimension'])) {
return new WP_Error('rest_invalid', esc_html__('[REST API] The <code>dimension</code> parameter is required. Please review your request and try again.', 'wp-slimstat'), ['status' => 400]);
}
if (empty($_request['function'])) {
return new WP_Error('rest_invalid', esc_html__('[REST API] The <code>function</code> parameter is required. Please review your request and try again.', 'wp-slimstat'), ['status' => 400]);
}
include_once(plugin_dir_path(__FILE__) . 'admin/view/wp-slimstat-db.php');
wp_slimstat_db::init($filters);
$response = [
'function' => htmlentities($_request['function'], ENT_QUOTES, 'UTF-8'),
'dimension' => htmlentities($_request['dimension'], ENT_QUOTES, 'UTF-8'),
'data' => 0,
];
switch ($_request['function']) {
case 'count':
case 'count-all':
$response['data'] = wp_slimstat_db::count_records($_request['dimension'], '', false === strpos($_request['function'], '-all'));
break;
case 'recent':
case 'recent-all':
case 'top':
case 'top-all':
$function = 'get_' . str_replace('-all', '', $_request['function']);
// Retrieve the data
$response['data'] = array_values(wp_slimstat_db::$function($_request['dimension'], '', '', false === strpos($_request['function'], '-all')));
break;
default:
// This should never happen, because of the 'enum' condition for this parameter. But never say never...
$response['data'] = new WP_Error('rest_invalid', esc_html__('[REST API] You sent an invalid request. Accepted function values include: <code>count, count-all, recent, recent-all, top and top-all</code>. Please review your request and try again.', 'wp-slimstat'), ['status' => 400]);
break;
}
return rest_ensure_response($response);
}
// end rest_api_response
/**
* Implements a REST API authentication mechanism via token
*/
public static function rest_api_authorization($_request = [])
{
if (empty($_request['token'])) {
return new WP_Error('rest_invalid', esc_html__('[REST API] Please use a valid token in order to access the REST API endpoint at this URL.', 'wp-slimstat'), ['status' => 400]);
}
$valid_tokens = self::string_to_array(self::$settings['rest_api_tokens']);
foreach ($valid_tokens as $valid_token) {
if (is_string($valid_token) && is_string($_request['token']) && hash_equals($valid_token, $_request['token'])) {
return true;
}
}
return false;
}
// end rest_api_authorization
/**
* Registers a new REST API route for the Slimstat endpoint
*/
public static function register_rest_route()
{
register_rest_route('slimstat/v1', '/get', [
'methods' => WP_REST_Server::READABLE,
'callback' => [self::class, 'rest_api_response'],
'permission_callback' => [self::class, 'rest_api_authorization'],
'args' => [
'token' => [
'description' => __('You will need to specify a valid token to be able to query the data. Tokens are defined in Slimstat > Settings > Access Control.', 'wp-slimstat'),
'type' => 'string',
],
'function' => [
'description' => __('This parameter specifies the type of QUERY you would like to perform. Accepted funciton values include: count, count-all, recent, recent-all, top and top-all.', 'wp-slimstat'),
'type' => 'string',
'enum' => ['count', 'count-all', 'recent', 'recent-all', 'top', 'top-all'],
],
'dimension' => [
'description' => __('This parameter indicates what dimension to return: * (all data), ip, resource, browser, operating system, etc. You can only specify one dimension at a time.', 'wp-slimstat'),
'type' => 'string',
'enum' => ['*', 'id', 'ip', 'username', 'email', 'country', 'referer', 'resource', 'searchterms', 'browser', 'platform', 'language', 'resolution', 'content_type', 'content_id', 'tz_offset', 'outbound_resource'],
],
'filters' => [
'description' => __('This parameter is used to filter a given dimension (resources, browsers, operating systems, etc) so that it satisfies certain conditions (i.e.: browser contains Chrome). Please make sure to urlencode this value, and to use the usual filter format: browser contains Chrome&&&referer contains slim (encoded: browser%20contains%20Chrome%26%26%26referer%20contains%20slim)', 'wp-slimstat'),
'type' => 'string',
],
],
]);
}
// end register_rest_route
/**
* Converts a series of comma separated values into an array
*/
public static function string_to_array($_option = '')
{
if (empty($_option) || !is_string($_option)) {
return [];
} else {
return array_filter(array_map('trim', explode(',', $_option)));
}
}
// end string_to_array
/**
* Returns Matomo search engine mapping JSON, cached.
*/
public static function get_search_engines()
{
static $cached_search_engines = null;
if (null !== $cached_search_engines) {
return $cached_search_engines;
}
$data = get_transient('slimstat_matomo_searchengine');
if (false === $data) {
$json_path = plugin_dir_path(__FILE__) . 'admin/assets/data/matomo-searchengine.json';
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents -- Local plugin file, WP_Filesystem not needed
$json = @file_get_contents($json_path);
$data = json_decode($json, true);
if (!is_array($data)) {
$data = [];
}
set_transient('slimstat_matomo_searchengine', $data, WEEK_IN_SECONDS);
}
$cached_search_engines = $data;
return $cached_search_engines;
}
// end get_search_engines
/**
* Toggles WordPress filters on date_i18n function
*/
public static function toggle_date_i18n_filters($_turn_on = true)
{
if ($_turn_on && !empty(self::$date_i18n_filters) && is_array(self::$date_i18n_filters)) {
foreach (self::$date_i18n_filters as $i18n_priority => $i18n_func_list) {
foreach ($i18n_func_list as $func_args) {
if (!empty($func_args['function']) && is_string($func_args['function'])) {
add_filter('date_i8n', $func_args['function'], $i18n_priority, intval($func_args['accepted_args']));
}
}
}
} elseif (!empty($GLOBALS['wp_filter']['date_i18n']['callbacks']) && is_array($GLOBALS['wp_filter']['date_i18n']['callbacks'])) {
self::$date_i18n_filters = $GLOBALS['wp_filter']['date_i18n']['callbacks'];
remove_all_filters('date_i18n');
}
}
// end toggle_date_i18n_filters
/**
* Calls the date_i18n function without filters
*/
public static function date_i18n($_format)
{
self::toggle_date_i18n_filters(false);
$date = date_i18n($_format);
self::toggle_date_i18n_filters(true);
return $date;
}
// end date_i18n
/**
* Returns default options with fresh-install additions (e.g. geolocation_provider).
* Used by init() for new installs and by admin reset-settings.
*/
public static function get_fresh_defaults()
{
$defaults = self::init_options();
$defaults['geolocation_provider'] = 'dbip';
return $defaults;
}
/**
* Returns the current geolocation precision ('country' or 'city').
*/
public static function get_geolocation_precision()
{
return ('on' == self::$settings['geolocation_country']) ? 'country' : 'city';
}
/**
* Sets the default values for all the options
*/
public static function init_options()
{
return [
'version' => SLIMSTAT_ANALYTICS_VERSION,
'secret' => wp_hash(wp_generate_password(64, true, true)),
'browscap_last_modified' => 0,
// General
// -----------------------------------------------------------------------
// General - Tracker
'is_tracking' => 'on',
'track_admin_pages' => 'no',
'javascript_mode' => 'off', // Changed: Enable server-side tracking by default
// General - WordPress Integration
'add_dashboard_widgets' => 'on',
'use_separate_menu' => 'on',
'add_posts_column' => 'no',
'posts_column_pageviews' => 'on',
'display_notifications' => 'on',
// General - Database
'auto_purge' => 420,
'auto_purge_delete' => 'on',
// Tracker
// -----------------------------------------------------------------------
// Tracker - Data Protection
// anonymize_ip: mask IP before storing; hash_ip: generate daily visitor_id based on masked IP + UA
'gdpr_enabled' => 'on', // Changed: Enable GDPR by default for safety
'anonymize_ip' => 'on', // Changed: Anonymize IPs by default
'hash_ip' => 'on', // Changed: Hash IPs by default
'set_tracker_cookie' => 'off', // Changed: Don't set cookies by default (GDPR-safe)
'use_slimstat_banner' => 'on', // Changed: Enable banner by default when GDPR is enabled
'consent_integration' => 'slimstat_banner', // Changed: Use SlimStat banner by default when GDPR is enabled
'consent_level_integration'=> 'statistics',
'opt_out_message' => '',
'gdpr_accept_button_text' => __('Accept', 'wp-slimstat'),
'gdpr_decline_button_text' => __('Decline', 'wp-slimstat'),
'gdpr_theme_mode' => 'auto', // 'light', 'dark', 'auto'
'anonymous_tracking' => 'off', // Changed: Enable anonymous tracking by default
'do_not_track' => 'off',
'display_opt_out' => 'no',
'opt_out_cookie_names' => '',
'opt_in_cookie_names' => '',
// Tracker - Link Tracking
'track_same_domain_referers' => 'no',
'do_not_track_outbound_classes_rel_href' => 'noslimstat,ab-item',
'extensions_to_track' => 'pdf,doc,xls,zip',
// Tracker - Advanced Options
'geolocation_country' => 'on',
'session_duration' => 1800,
'extend_session' => 'no',
'enable_cdn' => 'no',
'ajax_relative_path' => 'no',
// Tracker - External Pages
'external_domains' => '',
// Reports
// -----------------------------------------------------------------------
// Reports - Functionality
'use_current_month_timespan' => 'no',
'posts_column_day_interval' => 28,
'rows_to_show' => '20',
'show_hits' => 'no',
'ip_lookup_service' => 'https://ip-api.com/#',
'comparison_chart' => 'on',
'show_display_name' => 'no',
'convert_resource_urls_to_titles' => 'on',
'convert_ip_addresses' => 'no',
// Reports - Access Log and World Map
'refresh_interval' => '60',
'number_results_raw_data' => '50',
'max_dots_on_map' => '50',
// Reports - Miscellaneous
'custom_css' => '',
'chart_colors' => '',
'mozcom_access_id' => '',
'mozcom_secret_key' => '',
'show_complete_user_agent_tooltip' => 'no',
'async_load' => 'no',
'limit_results' => '200',
'enable_sov' => 'no',
// Exclusions
// -----------------------------------------------------------------------
// Exclusions - User Properties
'ignore_wp_users' => 'no',
'ignore_spammers' => 'on',
'ignore_bots' => 'no',
'ignore_prefetch' => 'on',
'ignore_users' => '',
'ignore_ip' => '',
'ignore_countries' => '',
'ignore_languages' => '',
'ignore_browsers' => '',
'ignore_platforms' => '',
'ignore_capabilities' => '',
// Exclusions - Page Properties
'ignore_resources' => '',
'ignore_referers' => '',
'ignore_content_types' => '',
// Access Control
// -----------------------------------------------------------------------
// Access Control - Reports
'restrict_authors_view' => 'on',
'capability_can_view' => 'manage_options',
'can_view' => '',
// Access Control - Reports
'tracking_request_method' => 'ajax',
// Access Control - Customizer
'capability_can_customize' => 'manage_options',
'can_customize' => '',
// Access Control - Settings
'capability_can_admin' => 'manage_options',
'can_admin' => '',
// Access Control - REST API
'rest_api_tokens' => wp_hash(wp_generate_password(64, true, true)),
// Maintenance
// -----------------------------------------------------------------------
'last_tracker_error' => [0, '', 0],
'show_sql_debug' => 'no',
'db_indexes' => 'on',
'enable_maxmind' => 'disable',
'maxmind_license_key' => '',
'enable_browscap' => 'no',
// Notices
// -----------------------------------------------------------------------
'notice_latest_news' => 'on',
'notice_browscap' => 'on',
'notice_geolite' => 'on',
'notice_caching' => 'on',
// Network-wide Settings
'locked_options' => '',
];
}
// end init_options
/**
* Saves a given option in the database
*/
public static function update_option($_key = '', $_value = '')
{
if (!is_network_admin()) {
update_option($_key, $_value);
} else {
update_site_option($_key, $_value);
}
}
// end update_option