-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.php
More file actions
1653 lines (1419 loc) · 53.6 KB
/
Copy pathfunctions.php
File metadata and controls
1653 lines (1419 loc) · 53.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
declare(strict_types=1);
require_once __DIR__ . '/config.php';
// Polyfill for environments where mbstring is not available
if (!function_exists('mb_strtolower')) {
function mb_strtolower(string $s, string $enc = 'UTF-8'): string
{
return strtolower($s);
}
}
if (PHP_SAPI !== 'cli' && session_status() !== PHP_SESSION_ACTIVE) {
session_name(SESSION_NAME);
session_start([
'cookie_httponly' => true,
'cookie_samesite' => 'Lax',
'use_strict_mode' => true,
]);
}
function ensure_runtime_paths(): void
{
foreach ([CACHE_DIR, UPLOADS_DIR] as $directory) {
if (!is_dir($directory)) {
mkdir($directory, 0775, true);
}
}
}
function database(): PDO
{
static $pdo = null;
if ($pdo instanceof PDO) {
return $pdo;
}
ensure_runtime_paths();
$needsInit = !file_exists(DB_PATH);
$pdo = new PDO('sqlite:' . DB_PATH);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$pdo->exec('PRAGMA foreign_keys = ON');
if ($needsInit || !tables_exist($pdo)) {
initialize_database($pdo);
}
return $pdo;
}
function tables_exist(PDO $pdo): bool
{
$tables = ['subscriptions', 'plans', 'settings'];
foreach ($tables as $table) {
$stmt = $pdo->prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = :name");
$stmt->execute(['name' => $table]);
if (!$stmt->fetchColumn()) {
return false;
}
}
return true;
}
function initialize_database(?PDO $pdo = null): void
{
$pdo ??= database();
$schema = file_get_contents(SCHEMA_PATH);
if ($schema === false) {
throw new RuntimeException('Unable to read schema.sql');
}
$pdo->exec($schema);
$defaults = [
'json_source_url' => DEFAULT_JSON_SOURCE_URL,
'vpn_name' => 'XAMBoost VPN',
'vpn_description' => 'Fast self-updating VPN subscription panel.',
'logo_url' => '',
'accent_color' => '#22c55e',
'server_renames' => '{}',
'use_manual_servers' => '0',
'manual_servers' => '',
'response_format' => 'happ',
];
foreach ($defaults as $key => $value) {
if (get_setting($key) === null) {
set_setting($key, $value);
}
}
}
function app_is_installed(): bool
{
try {
return get_setting('admin_username') !== null
&& get_setting('admin_password_hash') !== null
&& get_setting('api_token_hash') !== null;
} catch (Throwable $exception) {
return false;
}
}
function app_base_path(): string
{
$scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
$directory = str_replace('\\', '/', dirname($scriptName));
if ($directory === '/' || $directory === '.' || $directory === '\\') {
return '';
}
return rtrim($directory, '/');
}
function app_origin(): string
{
$https = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
$scheme = $https ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
return $scheme . '://' . $host;
}
function app_url(string $path = ''): string
{
$base = app_base_path();
$cleanPath = ltrim($path, '/');
return $base . ($cleanPath !== '' ? '/' . $cleanPath : '');
}
function absolute_app_url(string $path = ''): string
{
return app_origin() . app_url($path);
}
function redirect(string $path): never
{
header('Location: ' . (str_starts_with($path, 'http') ? $path : app_url($path)));
exit;
}
function get_setting(string $key, ?string $default = null): ?string
{
$stmt = database()->prepare('SELECT value FROM settings WHERE key = :key LIMIT 1');
$stmt->execute(['key' => $key]);
$value = $stmt->fetchColumn();
return $value === false ? $default : (string) $value;
}
function set_setting(string $key, string $value): void
{
$stmt = database()->prepare(
'INSERT INTO settings (key, value) VALUES (:key, :value)
ON CONFLICT(key) DO UPDATE SET value = excluded.value'
);
$stmt->execute([
'key' => $key,
'value' => $value,
]);
}
function set_settings(array $settings): void
{
foreach ($settings as $key => $value) {
set_setting((string) $key, (string) $value);
}
}
function get_branding_settings(): array
{
return [
'vpn_name' => get_setting('vpn_name', 'XAMBoost VPN') ?? 'XAMBoost VPN',
'vpn_description' => get_setting('vpn_description', 'Fast self-updating VPN subscription panel.') ?? '',
'logo_url' => get_setting('logo_url', '') ?? '',
'accent_color' => get_setting('accent_color', '#22c55e') ?? '#22c55e',
];
}
function json_setting_array(string $key, array $default = []): array
{
$raw = get_setting($key);
if ($raw === null || trim($raw) === '') {
return $default;
}
$decoded = json_decode($raw, true);
return is_array($decoded) ? $decoded : $default;
}
function flash(string $type, string $message): void
{
$_SESSION['flash'][] = [
'type' => $type,
'message' => $message,
];
}
function consume_flash(): array
{
$messages = $_SESSION['flash'] ?? [];
unset($_SESSION['flash']);
return is_array($messages) ? $messages : [];
}
function csrf_token(): string
{
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
return (string) $_SESSION['csrf_token'];
}
function verify_csrf(): void
{
$token = $_POST['_csrf'] ?? '';
if (!is_string($token) || !hash_equals(csrf_token(), $token)) {
throw new RuntimeException('Invalid CSRF token.');
}
}
function is_logged_in(): bool
{
return !empty($_SESSION['admin_logged_in']);
}
function require_setup_complete(): void
{
if (!app_is_installed() && basename($_SERVER['PHP_SELF'] ?? '') !== 'setup.php') {
redirect('setup.php');
}
}
function require_admin(): void
{
require_setup_complete();
if (!is_logged_in()) {
redirect('login.php');
}
}
function logout_admin(): void
{
$_SESSION = [];
if (ini_get('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 3600, $params['path'], $params['domain'] ?? '', (bool) ($params['secure'] ?? false), (bool) ($params['httponly'] ?? true));
}
session_destroy();
}
function now_utc(): string
{
return gmdate('Y-m-d H:i:s');
}
function now_timestamp(): int
{
return time();
}
function parse_datetime_to_utc(?string $value): ?string
{
if ($value === null || trim($value) === '') {
return null;
}
try {
$date = new DateTimeImmutable($value, new DateTimeZone('UTC'));
} catch (Throwable $exception) {
try {
$date = new DateTimeImmutable($value);
} catch (Throwable $inner) {
return null;
}
}
return $date->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s');
}
function uuid_v4(): string
{
$data = random_bytes(16);
$data[6] = chr((ord($data[6]) & 0x0f) | 0x40);
$data[8] = chr((ord($data[8]) & 0x3f) | 0x80);
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
function subscription_public_id(): string
{
return str_replace('-', '', uuid_v4());
}
function rate_limit(string $scope, int $limit, int $windowSeconds = 60): bool
{
ensure_runtime_paths();
$ip = $_SERVER['REMOTE_ADDR'] ?? 'cli';
$bucket = (int) floor(time() / $windowSeconds);
$path = CACHE_DIR . '/ratelimit_' . sha1($scope . '|' . $ip . '|' . $bucket) . '.json';
$count = 0;
if (file_exists($path)) {
$decoded = json_decode((string) file_get_contents($path), true);
$count = (int) ($decoded['count'] ?? 0);
}
$count++;
file_put_contents($path, json_encode(['count' => $count, 'updated_at' => now_utc()], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX);
return $count <= $limit;
}
function request_header(string $name): ?string
{
$normalized = 'HTTP_' . strtoupper(str_replace('-', '_', $name));
if (isset($_SERVER[$normalized])) {
return trim((string) $_SERVER[$normalized]);
}
if (function_exists('getallheaders')) {
foreach (getallheaders() as $headerName => $value) {
if (strcasecmp($headerName, $name) === 0) {
return trim((string) $value);
}
}
}
return null;
}
function json_response($data, int $status = 200): never
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
exit;
}
function error_response(string $message, int $status = 400, array $extra = []): never
{
json_response(array_merge([
'ok' => false,
'error' => $message,
], $extra), $status);
}
function success_response(array $data = [], int $status = 200): never
{
json_response(array_merge(['ok' => true], $data), $status);
}
function html_escape(?string $value): string
{
return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
}
function slugify(string $value): string
{
$value = strtolower(trim($value));
$value = preg_replace('/[^a-z0-9]+/i', '-', $value) ?? '';
$value = trim($value, '-');
return $value !== '' ? $value : 'item';
}
function normalize_accent_color(string $value): string
{
$value = trim($value);
return preg_match('/^#[0-9a-fA-F]{6}$/', $value) ? $value : '#22c55e';
}
function render_shell_start(string $title, string $subtitle = '', bool $showNav = true): void
{
$brand = get_branding_settings();
$flashMessages = consume_flash();
$current = basename($_SERVER['PHP_SELF'] ?? '');
$navItems = [
'dashboard.php' => ['label' => 'Dashboard', 'url' => app_url('dashboard')],
'subscriptions.php' => ['label' => 'Subscriptions', 'url' => app_url('subscriptions')],
'plans.php' => ['label' => 'Plans', 'url' => app_url('plans')],
'settings.php' => ['label' => 'Settings', 'url' => app_url('settings')],
];
echo '<!doctype html><html lang="en"><head><meta charset="utf-8">';
echo '<meta name="viewport" content="width=device-width, initial-scale=1">';
echo '<title>' . html_escape($title . ' • ' . $brand['vpn_name']) . '</title>';
echo '<script src="https://cdn.tailwindcss.com"></script>';
echo '<script>tailwind.config={theme:{extend:{colors:{accent:"' . html_escape($brand['accent_color']) . '"}}}}</script>';
echo '<link rel="preconnect" href="https://fonts.googleapis.com">';
echo '<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>';
echo '<link href="https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&display=swap" rel="stylesheet">';
echo '<style>
:root{--accent:' . html_escape($brand['accent_color']) . ';}
body{font-family:Manrope,system-ui,sans-serif;background:
radial-gradient(circle at top left, rgba(255,255,255,.35), transparent 32%),
radial-gradient(circle at bottom right, rgba(34,197,94,.18), transparent 28%),
linear-gradient(135deg, #f4f7fb 0%, #edf4f1 42%, #eef2ff 100%);}
.glass{background:rgba(255,255,255,.62);backdrop-filter:blur(20px);-webkit-backdrop-filter:blur(20px);border:1px solid rgba(255,255,255,.55);box-shadow:0 20px 60px rgba(15,23,42,.08);}
.glass-dark{background:rgba(15,23,42,.68);backdrop-filter:blur(18px);-webkit-backdrop-filter:blur(18px);}
.text-accent{color:var(--accent);}
.bg-accent{background-color:var(--accent);}
.ring-accent{--tw-ring-color:var(--accent);}
.border-accent{border-color:var(--accent);}
.btn-primary{background:linear-gradient(135deg,var(--accent),#0f172a);color:#fff;}
.btn-primary:hover{filter:brightness(1.04);}
.nav-pill{transition:.2s ease;}
.nav-pill:hover{transform:translateY(-1px);}
</style>';
echo '</head><body class="min-h-screen text-slate-900">';
echo '<div class="mx-auto w-full max-w-7xl px-4 py-6 sm:px-6 lg:px-8">';
echo '<div class="mb-6 glass rounded-[28px] p-5 sm:p-6">';
echo '<div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">';
echo '<div class="flex items-center gap-4">';
if ($brand['logo_url'] !== '') {
echo '<img src="' . html_escape($brand['logo_url']) . '" alt="Logo" class="h-14 w-14 rounded-2xl object-cover shadow-lg">';
} else {
echo '<div class="flex h-14 w-14 items-center justify-center rounded-2xl text-lg font-bold text-white shadow-lg" style="background:linear-gradient(135deg,' . html_escape($brand['accent_color']) . ',#0f172a)">VPN</div>';
}
echo '<div>';
echo '<p class="text-xs font-semibold uppercase tracking-[0.28em] text-slate-500">VPN SaaS Panel</p>';
echo '<h1 class="text-2xl font-extrabold tracking-tight text-slate-900">' . html_escape($title) . '</h1>';
if ($subtitle !== '') {
echo '<p class="mt-1 max-w-2xl text-sm text-slate-600">' . html_escape($subtitle) . '</p>';
}
echo '</div></div>';
if ($showNav) {
echo '<div class="flex flex-wrap items-center gap-2">';
foreach ($navItems as $file => $item) {
$active = $current === $file;
$classes = $active
? 'nav-pill rounded-full px-4 py-2 text-sm font-semibold text-white shadow-md'
: 'nav-pill rounded-full px-4 py-2 text-sm font-semibold text-slate-700';
$style = $active ? ' style="background:linear-gradient(135deg,' . html_escape($brand['accent_color']) . ',#0f172a)"' : '';
echo '<a class="' . $classes . '"' . $style . ' href="' . html_escape($item['url']) . '">' . html_escape($item['label']) . '</a>';
}
echo '<a class="nav-pill rounded-full px-4 py-2 text-sm font-semibold text-slate-700" href="' . html_escape(app_url('logout.php')) . '">Logout</a>';
echo '</div>';
}
echo '</div></div>';
foreach ($flashMessages as $flash) {
$tone = ($flash['type'] ?? 'info') === 'success'
? 'border-emerald-200 bg-emerald-50 text-emerald-800'
: (($flash['type'] ?? 'info') === 'error' ? 'border-rose-200 bg-rose-50 text-rose-800' : 'border-sky-200 bg-sky-50 text-sky-800');
echo '<div class="mb-4 rounded-2xl border px-4 py-3 text-sm font-medium ' . $tone . '">' . html_escape((string) ($flash['message'] ?? '')) . '</div>';
}
}
function render_shell_end(): void
{
echo '</div></body></html>';
}
function render_form_input(string $label, string $name, string $value = '', string $type = 'text', bool $required = false, string $placeholder = ''): void
{
echo '<label class="block">';
echo '<span class="mb-2 block text-sm font-semibold text-slate-700">' . html_escape($label) . '</span>';
echo '<input type="' . html_escape($type) . '" name="' . html_escape($name) . '" value="' . html_escape($value) . '" placeholder="' . html_escape($placeholder) . '" class="w-full rounded-2xl border border-white/60 bg-white/70 px-4 py-3 text-sm text-slate-900 shadow-sm outline-none transition focus:border-slate-300 focus:ring-2 focus:ring-slate-200" ' . ($required ? 'required' : '') . '>';
echo '</label>';
}
function render_form_textarea(string $label, string $name, string $value = '', int $rows = 4, string $placeholder = ''): void
{
echo '<label class="block">';
echo '<span class="mb-2 block text-sm font-semibold text-slate-700">' . html_escape($label) . '</span>';
echo '<textarea name="' . html_escape($name) . '" rows="' . $rows . '" placeholder="' . html_escape($placeholder) . '" class="w-full rounded-2xl border border-white/60 bg-white/70 px-4 py-3 text-sm text-slate-900 shadow-sm outline-none transition focus:border-slate-300 focus:ring-2 focus:ring-slate-200">' . html_escape($value) . '</textarea>';
echo '</label>';
}
function setup_guard_or_redirect(): void
{
if (!app_is_installed()) {
return;
}
redirect('dashboard');
}
function login_admin(string $username, string $password): bool
{
$storedUsername = get_setting('admin_username');
$storedHash = get_setting('admin_password_hash');
if ($storedUsername === null || $storedHash === null) {
return false;
}
if (!hash_equals($storedUsername, $username)) {
return false;
}
if (!password_verify($password, $storedHash)) {
return false;
}
session_regenerate_id(true);
$_SESSION['admin_logged_in'] = true;
$_SESSION['admin_username'] = $username;
return true;
}
function get_api_token_from_request(): ?string
{
$authorization = request_header('Authorization');
if ($authorization !== null && preg_match('/Bearer\s+(.+)/i', $authorization, $matches)) {
return trim($matches[1]);
}
$headerToken = request_header('X-API-Token');
if ($headerToken !== null && $headerToken !== '') {
return $headerToken;
}
$queryToken = $_GET['token'] ?? $_POST['token'] ?? null;
return is_string($queryToken) && $queryToken !== '' ? $queryToken : null;
}
function require_api_token(): void
{
if (!rate_limit('api', API_RATE_LIMIT)) {
error_response('Rate limit exceeded. Try again in a minute.', 429);
}
$token = get_api_token_from_request();
$hash = get_setting('api_token_hash');
if ($token === null || $hash === null || !password_verify($token, $hash)) {
error_response('Invalid API token.', 401);
}
}
function fetch_remote_json_source(): array
{
ensure_runtime_paths();
$url = get_setting('json_source_url', DEFAULT_JSON_SOURCE_URL) ?? DEFAULT_JSON_SOURCE_URL;
$cacheKey = sha1($url);
$cachePath = CACHE_DIR . '/source_' . $cacheKey . '.json';
$metaPath = CACHE_DIR . '/source_' . $cacheKey . '.meta.json';
$now = time();
$cachedRaw = file_exists($cachePath) ? (string) file_get_contents($cachePath) : null;
$meta = file_exists($metaPath) ? json_decode((string) file_get_contents($metaPath), true) : [];
$fetchedAt = (int) ($meta['fetched_at'] ?? 0);
if ($cachedRaw !== null && ($now - $fetchedAt) < CACHE_TTL_SECONDS) {
$decoded = json_decode($cachedRaw, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('Cached source JSON is invalid.');
}
return [
'url' => $url,
'raw' => $cachedRaw,
'decoded' => $decoded,
'cached' => true,
'stale' => false,
'fetched_at' => $fetchedAt,
];
}
$raw = download_url($url);
if ($raw !== null) {
$decoded = json_decode($raw, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('Source JSON could not be decoded: ' . json_last_error_msg());
}
file_put_contents($cachePath, $raw, LOCK_EX);
file_put_contents($metaPath, json_encode(['fetched_at' => $now, 'url' => $url], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), LOCK_EX);
return [
'url' => $url,
'raw' => $raw,
'decoded' => $decoded,
'cached' => false,
'stale' => false,
'fetched_at' => $now,
];
}
if ($cachedRaw !== null) {
$decoded = json_decode($cachedRaw, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('Stale cache JSON is invalid.');
}
return [
'url' => $url,
'raw' => $cachedRaw,
'decoded' => $decoded,
'cached' => true,
'stale' => true,
'fetched_at' => $fetchedAt,
];
}
throw new RuntimeException('Unable to fetch the remote source and no cache is available.');
}
function download_url(string $url): ?string
{
if (function_exists('curl_init')) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_CONNECTTIMEOUT => 10,
CURLOPT_USERAGENT => APP_NAME . '/' . APP_VERSION,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_HTTPHEADER => ['Accept: application/json'],
]);
$response = curl_exec($ch);
$status = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($response !== false && $status >= 200 && $status < 300) {
return (string) $response;
}
if ($error !== '') {
return null;
}
}
$context = stream_context_create([
'http' => [
'method' => 'GET',
'timeout' => 15,
'ignore_errors' => true,
'header' => "Accept: application/json\r\nUser-Agent: " . APP_NAME . '/' . APP_VERSION . "\r\n",
],
]);
$response = @file_get_contents($url, false, $context);
return $response === false ? null : $response;
}
function extract_server_uris($value, array &$collector = []): array
{
$schemes = ['vless://', 'vmess://', 'trojan://', 'ss://'];
if (is_string($value)) {
$trimmed = trim($value);
foreach ($schemes as $scheme) {
if (stripos($trimmed, $scheme) === 0) {
$collector[$trimmed] = $trimmed;
break;
}
}
return array_values($collector);
}
if (is_array($value)) {
foreach ($value as $item) {
extract_server_uris($item, $collector);
}
}
return array_values($collector);
}
function parse_proxy_uri(string $uri): ?array
{
$parts = parse_url($uri);
if ($parts === false || empty($parts['scheme'])) {
return null;
}
$scheme = strtolower((string) $parts['scheme']);
if ($scheme === 'vless' || $scheme === 'trojan') {
parse_str((string) ($parts['query'] ?? ''), $query);
$fragment = isset($parts['fragment']) ? urldecode((string) $parts['fragment']) : '';
return [
'scheme' => $scheme,
'raw' => $uri,
'user' => (string) ($parts['user'] ?? ''),
'password' => (string) ($parts['pass'] ?? ''),
'host' => (string) ($parts['host'] ?? ''),
'port' => isset($parts['port']) ? (int) $parts['port'] : null,
'query' => $query,
'name' => trim($fragment),
];
}
if ($scheme === 'ss') {
$fragment = '';
if (str_contains($uri, '#')) {
[, $fragment] = explode('#', $uri, 2);
$fragment = urldecode($fragment);
}
$withoutFragment = explode('#', $uri, 2)[0];
$body = substr($withoutFragment, strlen('ss://'));
$decoded = base64_decode(strtr($body, '-_', '+/'), true);
if ($decoded === false) {
$bodyParts = explode('@', $body, 2);
if (count($bodyParts) !== 2) {
return null;
}
$left = $bodyParts[0];
$right = $bodyParts[1];
} else {
$bodyParts = explode('@', $decoded, 2);
if (count($bodyParts) !== 2) {
return null;
}
$left = $bodyParts[0];
$right = $bodyParts[1];
}
[$method, $password] = array_pad(explode(':', $left, 2), 2, '');
[$host, $port] = array_pad(explode(':', $right, 2), 2, '');
return [
'scheme' => 'ss',
'raw' => $uri,
'method' => $method,
'password' => $password,
'host' => $host,
'port' => (int) $port,
'name' => trim($fragment),
'query' => [],
];
}
return null;
}
function clean_server_label(string $label): string
{
$label = preg_replace('/\s+/', ' ', trim($label)) ?? '';
return $label !== '' ? $label : 'VPN Server';
}
function server_rename_for(array $candidates, array $mapping): ?string
{
foreach ($candidates as $candidate) {
$candidate = trim((string) $candidate);
if ($candidate === '') {
continue;
}
if (isset($mapping[$candidate]) && trim((string) $mapping[$candidate]) !== '') {
return trim((string) $mapping[$candidate]);
}
}
return null;
}
function singbox_transport_from_query(array $query): ?array
{
$type = strtolower((string) ($query['type'] ?? 'tcp'));
if ($type === '' || $type === 'tcp') {
return null;
}
if ($type === 'ws') {
$transport = ['type' => 'ws'];
if (!empty($query['path'])) {
$transport['path'] = (string) $query['path'];
}
// Prefer explicit `host` param, fallback to `sni` when present.
$host = (string) ($query['host'] ?? '');
if ($host === '' && !empty($query['sni'])) {
$host = (string) $query['sni'];
}
if ($host !== '') {
$transport['headers'] = ['Host' => $host];
}
return $transport;
}
if ($type === 'grpc') {
$transport = ['type' => 'grpc'];
if (!empty($query['serviceName'])) {
$transport['service_name'] = (string) $query['serviceName'];
}
if (!empty($query['mode'])) {
$transport['mode'] = (string) $query['mode'];
}
return $transport;
}
if ($type === 'httpupgrade') {
return [
'type' => 'httpupgrade',
'host' => (string) ($query['host'] ?? ''),
'path' => (string) ($query['path'] ?? '/'),
];
}
if ($type === 'xhttp') {
$transport = [
'type' => 'http',
'path' => (string) ($query['path'] ?? '/'),
];
$host = (string) ($query['host'] ?? '');
if ($host !== '') {
$transport['host'] = [$host];
}
return $transport;
}
return ['type' => $type];
}
function singbox_tls_from_query(array $query, string $host): ?array
{
$security = strtolower((string) ($query['security'] ?? 'none'));
if (!in_array($security, ['tls', 'reality'], true)) {
return null;
}
$tls = [
'enabled' => true,
'server_name' => (string) ($query['sni'] ?? $host),
];
if (!empty($query['insecure']) && (string) $query['insecure'] !== '0') {
$tls['insecure'] = true;
}
if (!empty($query['alpn'])) {
$tls['alpn'] = array_values(array_filter(array_map('trim', explode(',', (string) $query['alpn']))));
}
if (!empty($query['fp'])) {
$tls['utls'] = [
'enabled' => true,
'fingerprint' => (string) $query['fp'],
];
}
if ($security === 'reality' && !empty($query['pbk'])) {
$tls['reality'] = [
'enabled' => true,
'public_key' => (string) $query['pbk'],
];
if (!empty($query['sid'])) {
$tls['reality']['short_id'] = (string) $query['sid'];
}
}
return $tls;
}
function singbox_outbound_from_server(array $parsed, int $index, array $renameMap): ?array
{
$name = clean_server_label($parsed['name'] ?: (($parsed['host'] ?? 'server') . ':' . ($parsed['port'] ?? '')));
$renamed = server_rename_for([
$parsed['name'] ?? '',
$parsed['host'] ?? '',
$parsed['raw'] ?? '',
], $renameMap);
$displayName = $renamed ?? $name;
$tag = slugify($displayName) . '-' . $index;
if (($parsed['scheme'] ?? '') === 'vless') {
$outbound = [
'type' => 'vless',
'tag' => $tag,
'server' => (string) $parsed['host'],
'server_port' => (int) ($parsed['port'] ?? 443),
'uuid' => (string) $parsed['user'],
];
if (!empty($parsed['query']['flow'])) {
$outbound['flow'] = (string) $parsed['query']['flow'];
}
$tls = singbox_tls_from_query($parsed['query'], (string) $parsed['host']);
if ($tls !== null) {
$outbound['tls'] = $tls;
}
$transport = singbox_transport_from_query($parsed['query']);
if ($transport !== null) {
$outbound['transport'] = $transport;
}
if (!empty($parsed['query']['packetEncoding'])) {
$outbound['packet_encoding'] = (string) $parsed['query']['packetEncoding'];
}
return [
'tag' => $tag,
'display_name' => $displayName,
'country' => infer_country_from_label($displayName),
'outbound' => $outbound,
];
}
if (($parsed['scheme'] ?? '') === 'trojan') {
$outbound = [
'type' => 'trojan',
'tag' => $tag,
'server' => (string) $parsed['host'],
'server_port' => (int) ($parsed['port'] ?? 443),
'password' => (string) $parsed['user'],
];
$tls = singbox_tls_from_query($parsed['query'], (string) $parsed['host']);
if ($tls !== null) {
$outbound['tls'] = $tls;
}
$transport = singbox_transport_from_query($parsed['query']);
if ($transport !== null) {
$outbound['transport'] = $transport;
}
return [
'tag' => $tag,
'display_name' => $displayName,
'country' => infer_country_from_label($displayName),
'outbound' => $outbound,
];
}
if (($parsed['scheme'] ?? '') === 'ss') {
$outbound = [
'type' => 'shadowsocks',
'tag' => $tag,
'server' => (string) $parsed['host'],
'server_port' => (int) ($parsed['port'] ?? 443),
'method' => (string) ($parsed['method'] ?? ''),
'password' => (string) ($parsed['password'] ?? ''),
];
return [
'tag' => $tag,
'display_name' => $displayName,
'country' => infer_country_from_label($displayName),
'outbound' => $outbound,
];
}
return null;
}
function infer_country_from_label(string $label): string
{
$normalized = trim(preg_replace('/[^\p{L}\p{N},\s-]+/u', '', $label) ?? '');
if ($normalized === '') {
return 'Unknown';
}
$parts = explode(',', $normalized);
$first = trim($parts[0]);
if ($first !== '') {
return $first;
}
$words = preg_split('/\s+/', $normalized) ?: [];
return trim(implode(' ', array_slice($words, 0, min(2, count($words))))) ?: 'Unknown';
}
function collect_countries_from_source(array $source): array
{
$countries = [];
foreach ($source as $key => $value) {
if ($key === 'updated_at') {
continue;
}
if ($key === 'other_countries' && is_array($value)) {
foreach ($value as $country => $countryPayload) {
if (is_array($countryPayload)) {
$countries[$country] = $country;
}
}
continue;
}
if ($key === 'w_other') {
continue;
}
if (is_array($value) && (array_key_exists('best', $value) || array_key_exists('top10', $value))) {
$countries[humanize_source_key((string) $key)] = humanize_source_key((string) $key);
}
}
foreach (extract_server_uris($source) as $uri) {
$parsed = parse_proxy_uri($uri);
if ($parsed !== null && !empty($parsed['name'])) {
$countries[infer_country_from_label((string) $parsed['name'])] = infer_country_from_label((string) $parsed['name']);
}
}
ksort($countries);
return array_values($countries);