-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStarUserEnv.php
More file actions
1105 lines (970 loc) · 32.6 KB
/
Copy pathStarUserEnv.php
File metadata and controls
1105 lines (970 loc) · 32.6 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
/**
* SPARXSTAR User Environment Check
*
* Shared utility helpers and public snapshot accessors for SPARXSTAR
* environment diagnostics.
*
* @package SparxstarUserEnvironmentCheck
* @copyright Copyright (c) 2023-2026, Starisian Technologies
* @license Proprietary. All Rights Reserved.
*/
declare(strict_types=1);
namespace Starisian\SparxstarUEC;
use Throwable;
use function __;
use function hash;
use function trim;
use function gmdate;
use function is_ssl;
use function strtok;
use function substr;
use function explode;
use function stripos;
use function is_array;
use function filter_var;
use function preg_match;
use function session_id;
use function strtolower;
use function wp_unslash;
use function esc_url_raw;
use function headers_sent;
use function str_contains;
use function apply_filters;
use function session_start;
use function session_status;
use function wp_json_encode;
use const FILTER_VALIDATE_IP;
use const PHP_SESSION_ACTIVE;
use function get_current_user_id;
use function sanitize_text_field;
use Starisian\SparxstarUEC\helpers\StarLogger;
use Starisian\SparxstarUEC\includes\SparxstarUECCacheHelper;
use Starisian\SparxstarUEC\core\SparxstarUECSnapshotRepository;
use Starisian\SparxstarUEC\includes\SparxstarUECSessionManager;
if (! defined('ABSPATH')) {
exit;
}
/**
* Collection of static helper methods for retrieving sanitized visitor metadata
* AND reading environment snapshots as the public API.
*/
final class StarUserEnv
{
/**
* Session namespace key used to avoid collisions with other plugins.
*/
private const SESSION_NAMESPACE = 'sparxstar_env';
/**
* Session storage key for the most recent environment snapshot.
*/
private const SESSION_KEY = 'sparxstar_env_snapshot';
/**
* Runtime cache for the current request's snapshot.
*/
private static ?array $snapshot_cache = null;
// -------------------------------------------------------------------------
// I. IDENTITY HELPERS (MODERN MODEL)
// -------------------------------------------------------------------------
/**
* Return the stable plugin fingerprint used by JS + DB.
* Priority: header → cookie → IP hash.
*/
public static function getFingerprint(): string
{
// 1. Header from JS (authoritative)
$header = self::get_server_value('HTTP_X_SPX_FINGERPRINT');
if ($header !== '') {
return sanitize_text_field($header);
}
// 2. Cookie (persistence)
if (isset($_COOKIE['spx_visitor_id'])) {
return sanitize_text_field(wp_unslash($_COOKIE['spx_visitor_id']));
}
// 3. Fallback to legacy (IP-based) fingerprint
return hash('sha256', self::getClientIP() ?: 'unknown');
}
/**
* Return stable device hash used as second identity key.
* Priority: header → UA+IP hash.
*/
public static function getDeviceHash(): string
{
$header = self::get_server_value('HTTP_X_SPX_DEVICE_HASH');
if ($header !== '') {
return sanitize_text_field($header);
}
// Fallback for backward compatibility
return hash('sha1', self::getUserAgent() . ':' . self::getClientIP());
}
// -------------------------------------------------------------------------
// II. SNAPSHOT FETCHING & CACHING (UNIFIED ENGINE)
// -------------------------------------------------------------------------
/**
* Retrieve the latest stored snapshot for a user/session (public).
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
* @return array<string, mixed>|null Snapshot payload when available.
*/
public static function get_snapshot(?int $user_id = null, ?string $session_id = null): ?array
{
return self::fetch_snapshot($user_id, $session_id);
}
/**
* Internal engine fetching snapshot from runtime cache/session/cache/DB.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
* @return array<string, mixed>|null Snapshot payload when available.
*/
private static function fetch_snapshot(?int $user_id, ?string $session_id): ?array
{
// --- 1. CHECK RUNTIME CACHE (Fastest) ---
if (self::$snapshot_cache !== null) {
return self::$snapshot_cache;
}
// --- 2. CHECK SESSION (Primary fix for REST API) ---
// If we're in an AJAX/REST context, the session will have the data if
// the user loaded the page immediately prior.
$session_stored = self::getEnvironmentSnapshot();
if (!empty($session_stored['snapshot'])) {
self::$snapshot_cache = $session_stored['snapshot'];
return self::$snapshot_cache;
}
// --- 3. CHECK DB/CACHE (Original UEC Logic) ---
$fingerprint = self::getFingerprint();
$device_hash = self::getDeviceHash();
$resolved_user_id = $user_id ?? (get_current_user_id() ?: null);
// Build cache key using BOTH fingerprint AND device_hash
$cache_key = SparxstarUECCacheHelper::make_key(
$resolved_user_id,
$session_id,
$fingerprint . ':' . $device_hash
);
$cached = SparxstarUECCacheHelper::get($cache_key);
if ($cached !== null) {
self::$snapshot_cache = $cached;
return $cached;
}
// Query database using v2.0 identity model
$from_db = SparxstarUECSnapshotRepository::get($fingerprint, $device_hash);
if ($from_db !== null) {
SparxstarUECCacheHelper::set($cache_key, $from_db);
self::$snapshot_cache = $from_db;
}
return $from_db;
}
/**
* Generic dot-path accessor into snapshot structure.
*
* @param string $path Dot-path into snapshot array.
* @param mixed $default Default value when missing.
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
* @return mixed Resolved value or default.
*/
private static function get_value_from_snapshot(
string $path,
mixed $default,
?int $user_id,
?string $session_id
): mixed {
$snapshot = self::fetch_snapshot($user_id, $session_id);
if ($snapshot === null) {
return $default;
}
$current = $snapshot;
foreach (explode('.', $path) as $key) {
if (! is_array($current) || ! isset($current[$key])) {
return $default;
}
$current = $current[$key];
}
return $current;
}
/**
* Flushes the cache for a given user, forcing the next getter call to fetch fresh data.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
*/
public static function flush_cache(?int $user_id = null, ?string $session_id = null): void
{
$resolved_user_id = $user_id ?? (get_current_user_id() ?: null);
$fingerprint = self::getFingerprint();
$device_hash = self::getDeviceHash();
$cache_key = SparxstarUECCacheHelper::make_key(
$resolved_user_id,
$session_id,
$fingerprint . ':' . $device_hash
);
SparxstarUECCacheHelper::delete($cache_key);
self::$snapshot_cache = null;
}
/**
* Retrieves the entire raw snapshot for debugging or full-data use cases.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
* @return array<string, mixed>|null Snapshot payload when available.
*/
public static function get_full_snapshot(?int $user_id = null, ?string $session_id = null): ?array
{
return self::fetch_snapshot($user_id, $session_id);
}
// -------------------------------------------------------------------------
// III. PUBLIC SNAPSHOT GETTERS (EX-STARUSERENV)
// -------------------------------------------------------------------------
// --- Identification & Tracking ---
/**
* Get the user's stable, anonymous browser fingerprint ID from the snapshot.
* This is the primary key for tracking anonymous users.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
*/
public static function get_visitor_id(?int $user_id = null, ?string $session_id = null): string
{
return (string) self::get_value_from_snapshot(
'identifiers.visitor_id',
'',
$user_id,
$session_id
);
}
// --- Performance & UX Optimization ---
/**
* Retrieve effective network type from the latest snapshot.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
*/
public static function get_network_type(?int $user_id = null, ?string $session_id = null): string
{
return (string) self::get_value_from_snapshot(
'client_side_data.network.effectiveType',
'unknown',
$user_id,
$session_id
);
}
/**
* Determine whether data-saver mode is enabled in snapshot data.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
*/
public static function is_data_saver_enabled(?int $user_id = null, ?string $session_id = null): bool
{
return (bool) self::get_value_from_snapshot(
'client_side_data.network.saveData',
false,
$user_id,
$session_id
);
}
/**
* Get normalized device type from snapshot.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
*/
public static function get_user_device(?int $user_id = null, ?string $session_id = null): string
{
return (string) self::get_value_from_snapshot(
'client_side_data.device.type',
'unknown',
$user_id,
$session_id
);
}
/**
* Get GPU identifier from snapshot fingerprinting data.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
*/
public static function get_user_gpu(?int $user_id = null, ?string $session_id = null): string
{
return (string) self::get_value_from_snapshot(
'client_side_data.fingerprint.gpu',
'unknown',
$user_id,
$session_id
);
}
/**
* Get operating system label from snapshot.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
*/
public static function get_os_name(?int $user_id = null, ?string $session_id = null): string
{
return (string) self::get_value_from_snapshot(
'client_side_data.os.name',
'unknown',
$user_id,
$session_id
);
}
/**
* Get browser name from snapshot.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
*/
public static function get_browser_name(?int $user_id = null, ?string $session_id = null): string
{
return (string) self::get_value_from_snapshot(
'client_side_data.client.name',
'unknown',
$user_id,
$session_id
);
}
// --- Geolocation & Localization (Snapshot-based) ---
/**
* Get server-observed user IP from snapshot.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
*/
public static function get_user_ip(?int $user_id = null, ?string $session_id = null): string
{
return (string) self::get_value_from_snapshot(
'server_side_data.ip_address',
'0.0.0.0',
$user_id,
$session_id
);
}
/**
* Get user country from snapshot geolocation block.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
*/
public static function get_user_country(?int $user_id = null, ?string $session_id = null): string
{
return (string) self::get_value_from_snapshot(
'server_side_data.geolocation.country',
'unknown',
$user_id,
$session_id
);
}
/**
* Get user region/state from snapshot geolocation block.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
*/
public static function get_user_state(?int $user_id = null, ?string $session_id = null): string
{
return (string) self::get_value_from_snapshot(
'server_side_data.geolocation.region',
'unknown',
$user_id,
$session_id
);
}
/**
* Get user city from snapshot geolocation block.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
*/
public static function get_user_city(?int $user_id = null, ?string $session_id = null): string
{
return (string) self::get_value_from_snapshot(
'server_side_data.geolocation.city',
'unknown',
$user_id,
$session_id
);
}
/**
* Get two-letter language code from snapshot context language.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
*/
public static function get_user_language(?int $user_id = null, ?string $session_id = null): string
{
$lang = (string) self::get_value_from_snapshot(
'client_side_data.context.language',
'',
$user_id,
$session_id
);
return substr($lang, 0, 2);
}
// --- Legal & Security ---
/**
* Get UTC timestamp of the stored snapshot.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
*/
public static function get_snapshot_timestamp(?int $user_id = null, ?string $session_id = null): string
{
return (string) self::get_value_from_snapshot(
'server_side_data.timestamp_utc',
'',
$user_id,
$session_id
);
}
/**
* Determine if geolocation data flagged VPN/proxy usage.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
*/
public static function is_on_vpn(?int $user_id = null, ?string $session_id = null): bool
{
return (bool) self::get_value_from_snapshot(
'server_side_data.geolocation.is_vpn',
false,
$user_id,
$session_id
);
}
/**
* Return active session ID from the session manager.
*/
public static function get_current_user_session_id(): string
{
return SparxstarUECSessionManager::get_session_id();
}
// --- Snapshot-based Geolocation Convenience (camelCase variants) ---
/**
* Get full geolocation payload from snapshot server block.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
* @return array<string, mixed> Geolocation map.
*/
public static function get_geolocation(?int $user_id = null, ?string $session_id = null): array
{
$geo = self::get_value_from_snapshot(
'server_side_data.geolocation',
[],
$user_id,
$session_id
);
return is_array($geo) ? $geo : [];
}
/**
* Geolocation convenience accessor for city.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
* @param string $default Default when value is missing.
*/
public static function get_city(
?int $user_id = null,
?string $session_id = null,
string $default = ''
): string {
return (string) self::get_value_from_snapshot(
'server_side_data.geolocation.city',
$default,
$user_id,
$session_id
);
}
/**
* Geolocation convenience accessor for state.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
* @param string $default Default when value is missing.
*/
public static function get_state(
?int $user_id = null,
?string $session_id = null,
string $default = ''
): string {
return (string) self::get_value_from_snapshot(
'server_side_data.geolocation.state',
$default,
$user_id,
$session_id
);
}
/**
* Geolocation convenience accessor for postal code.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
* @param string $default Default when value is missing.
*/
public static function get_postal_code(
?int $user_id = null,
?string $session_id = null,
string $default = ''
): string {
return (string) self::get_value_from_snapshot(
'server_side_data.geolocation.postal_code',
$default,
$user_id,
$session_id
);
}
/**
* Geolocation convenience accessor for region.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
* @param string $default Default when value is missing.
*/
public static function get_region(
?int $user_id = null,
?string $session_id = null,
string $default = ''
): string {
return (string) self::get_value_from_snapshot(
'server_side_data.geolocation.region',
$default,
$user_id,
$session_id
);
}
/**
* Geolocation convenience accessor for country.
*
* @param int|null $user_id Optional user scope.
* @param string|null $session_id Optional session scope.
* @param string $default Default when value is missing.
*/
public static function get_country(
?int $user_id = null,
?string $session_id = null,
string $default = ''
): string {
return (string) self::get_value_from_snapshot(
'server_side_data.geolocation.country',
$default,
$user_id,
$session_id
);
}
// -------------------------------------------------------------------------
// IV. SESSION + SERVER HELPERS (LEGACY + MODERN)
// -------------------------------------------------------------------------
/**
* Ensure a PHP session is initialised before attempting to read or write data.
*/
private static function ensure_session(): void
{
if (PHP_SESSION_ACTIVE === session_status()) {
self::initialise_namespace();
return;
}
if (headers_sent()) {
return;
}
$options = [
'name' => 'spxenv',
'cookie_httponly' => true,
'cookie_samesite' => 'Lax',
];
if (is_ssl()) {
$options['cookie_secure'] = true;
}
try {
session_start($options);
} catch (Throwable $throwable) {
StarLogger::error('StarUserEnv', $throwable, ['method' => 'ensure_session']);
return;
}
self::initialise_namespace();
}
/**
* Guarantee that the plugin-specific session namespace exists.
*/
private static function initialise_namespace(): void
{
if (! isset($_SESSION[self::SESSION_NAMESPACE]) || ! is_array($_SESSION[self::SESSION_NAMESPACE])) {
$_SESSION[self::SESSION_NAMESPACE] = [];
}
}
/**
* Retrieve a value from the $_SERVER superglobal with sanitization applied.
*
* @param string $key Server header/index key.
*/
private static function get_server_value(string $key): string
{
return isset($_SERVER[$key]) ? sanitize_text_field(wp_unslash($_SERVER[$key])) : '';
}
/**
* Sanitize and validate an IP address string.
*
* @param string|null $value Raw IP candidate string.
*/
private static function filter_ip_address(?string $value): string
{
if (! is_string($value)) {
return '';
}
$value = trim($value);
if ($value === '') {
return '';
}
if (str_contains($value, ',')) {
$value = strtok($value, ',');
}
$filtered_ip = filter_var(trim($value), FILTER_VALIDATE_IP);
return $filtered_ip ? trim($filtered_ip) : '';
}
/**
* Retrieve the client IP address considering proxy headers.
*/
public static function getClientIP(): string
{
$ip_headers = [
'HTTP_CF_CONNECTING_IP',
'HTTP_CLIENT_IP',
'HTTP_X_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_X_CLUSTER_CLIENT_IP',
'HTTP_FORWARDED_FOR',
'HTTP_FORWARDED',
'REMOTE_ADDR',
];
foreach ($ip_headers as $header) {
$value = self::get_server_value($header);
if ($value === '') {
continue;
}
$ips = array_map(trim(...), explode(',', $value));
foreach ($ips as $ip) {
$filtered_ip = self::filter_ip_address($ip);
if ($filtered_ip !== '') {
return $filtered_ip;
}
}
}
return '0.0.0.0';
}
/**
* Internal helper to get the LIVE IP of the CURRENT visitor.
* (alias for snapshot-independent IP lookup).
*/
public static function get_current_visitor_ip(): string
{
return self::getClientIP();
}
/**
* Persist an arbitrary value in the session namespace.
*
* @param string $key Session key.
* @param mixed $value Value to persist.
*/
public static function setSessionValue(string $key, mixed $value): void
{
self::ensure_session();
$_SESSION[self::SESSION_NAMESPACE][$key] = $value;
}
/**
* Retrieve a value from the session namespace.
*
* @param string $key Session key.
* @param mixed $default Default return when missing.
* @return mixed Resolved session value.
*/
public static function getSessionValue(string $key, mixed $default = null): mixed
{
self::ensure_session();
return $_SESSION[self::SESSION_NAMESPACE][$key] ?? $default;
}
/**
* Store an environment snapshot and its context within the PHP session.
*
* @param array<string, mixed> $snapshot Snapshot payload.
* @param array<string, mixed> $context Supplemental context metadata.
*/
public static function storeEnvironmentSnapshot(array $snapshot, array $context = []): void
{
self::ensure_session();
$_SESSION[self::SESSION_NAMESPACE][self::SESSION_KEY] = [
'snapshot' => $snapshot,
'context' => $context,
'stored_at' => gmdate('c'),
];
}
/**
* Retrieve the stored environment snapshot from the PHP session.
*/
public static function getEnvironmentSnapshot(): array
{
self::ensure_session();
$stored = $_SESSION[self::SESSION_NAMESPACE][self::SESSION_KEY] ?? [];
return is_array($stored) ? $stored : [];
}
/**
* Retrieve the active PHP session identifier when available.
*/
public static function getSessionID(): string
{
return PHP_SESSION_ACTIVE === session_status() ? (string) session_id() : '';
}
/**
* Access the current user agent string with sanitization applied.
*/
public static function getUserAgent(): string
{
return sanitize_text_field(self::get_server_value('HTTP_USER_AGENT'));
}
/**
* Build the current request URL using sanitized server globals.
*/
public static function getCurrentURL(): string
{
$host = self::get_server_value('HTTP_HOST');
$uri = self::get_server_value('REQUEST_URI');
if ($host === '' || $uri === '') {
return '';
}
$scheme = is_ssl() ? 'https://' : 'http://';
return esc_url_raw($scheme . $host . $uri);
}
/**
* Retrieve the referring URL from the request headers.
*/
public static function getReferrerURL(): string
{
$referer = self::get_server_value('HTTP_REFERER');
return $referer !== '' && $referer !== '0' ? esc_url_raw($referer) : '';
}
/**
* Fetch geolocation data using an external provider hooked via WordPress filters.
*
* @param string $ip Optional specific IP override.
* @return array<string, mixed> Provider geolocation payload.
*/
public static function getIPGeoLocation(string $ip = ''): array
{
$ip_to_lookup = $ip !== '' ? $ip : self::getClientIP();
$data = apply_filters('sparxstar_env_geolocation_lookup', null, $ip_to_lookup);
return is_array($data) ? $data : [];
}
/**
* Retrieve a specific field from the geolocation payload or the full JSON
* from the external provider (snapshot-independent).
*
* @param string $field Optional field key.
* @param string $ip Optional specific IP override.
*/
public static function getGeoLocationData(string $field = '', string $ip = ''): string
{
$location = self::getIPGeoLocation($ip);
if ($location === []) {
return __('Location data unavailable.', SPX_ENV_CHECK_TEXT_DOMAIN);
}
if ($field === '') {
return wp_json_encode($location, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
$map = [
'city' => 'city',
'region' => 'regionName',
'country' => 'countryName',
'country_code' => 'countryCode',
'latitude' => 'lat',
'longitude' => 'lon',
'zip' => 'zip',
'timezone' => 'timezone',
];
$key = $map[strtolower($field)] ?? null;
if ($key !== null && isset($location[$key])) {
return sanitize_text_field((string) $location[$key]);
}
return __('Specific location data unavailable.', SPX_ENV_CHECK_TEXT_DOMAIN);
}
/**
* Determine the preferred language from the Accept-Language header.
*
* @param string $ret_type Output type ('code' or full locale).
*/
public static function getUserLanguage(string $ret_type = 'code'): string
{
$raw = self::get_server_value('HTTP_ACCEPT_LANGUAGE');
if ($raw === '') {
return '';
}
$parts = explode(',', $raw);
$primary = trim(explode(';', $parts[0])[0]);
if (strtolower($ret_type) === 'code') {
return sanitize_text_field(substr($primary, 0, 2));
}
return sanitize_text_field($primary);
}
/**
* Determine the visitor operating system based on the User-Agent string.
*/
public static function getUserOS(): string
{
$user_agent = strtolower(self::getUserAgent());
$map = [
'windows' => 'Windows',
'macintosh|mac os x|macos' => 'Mac',
'linux' => 'Linux',
'ipad|ipod|iphone' => 'iOS',
'android' => 'Android',
'blackberry' => 'BlackBerry',
'webos' => 'webOS',
'windows phone' => 'Windows Phone',
];
foreach ($map as $needle => $label) {
if (preg_match('/' . $needle . '/', $user_agent)) {
return $label;
}
}
return 'Other';
}
/**
* Get the approximate browser name based on the User-Agent string.
*/
public static function getUserBrowser(): string
{
$user_agent = self::getUserAgent();
if (preg_match('/MSIE/i', $user_agent) && ! preg_match('/Opera/i', $user_agent)) {
return 'Internet Explorer';
}
if (preg_match('/Firefox/i', $user_agent)) {
return 'Firefox';
}
if (preg_match('/Chrome/i', $user_agent)) {
return 'Chrome';
}
if (preg_match('/Safari/i', $user_agent)) {
return 'Safari';
}
if (preg_match('/Opera/i', $user_agent)) {
return 'Opera';
}
if (preg_match('/Netscape/i', $user_agent)) {
return 'Netscape';
}
if (preg_match('/Edge/i', $user_agent)) {
return 'Edge';
}
if (preg_match('/CriOS/i', $user_agent)) {
return 'Chrome iOS';
}
if (preg_match('/FxiOS/i', $user_agent)) {
return 'Firefox iOS';
}
return 'Unknown';
}
/**
* Determine if the request is from a bot/crawler using common user agent patterns.
*/
public static function isBot(): bool
{
$user_agent = self::getUserAgent();
$bots = [
'googlebot',
'bingbot',
'yandexbot',
'duckduckbot',
'slurp',
'baiduspider',
'facebookexternalhit',