-
Notifications
You must be signed in to change notification settings - Fork 1
/
func.php
2645 lines (2284 loc) · 74.2 KB
/
func.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/** @noinspection PhpDefineCanBeReplacedWithConstInspection */
/** @noinspection RegExpRedundantEscape */
$isCli = (php_sapi_name() === 'cli' || defined('STDIN') || (empty($_SERVER['REMOTE_ADDR']) && !isset($_SERVER['HTTP_USER_AGENT']) && count($_SERVER['argv']) > 0));
if (!function_exists('str_starts_with')) {
/**
* Checks if a string starts with a given prefix using regular expressions.
*
* @param string $haystack The input string.
* @param string $needle The prefix to check for.
* @return bool Returns true if the string starts with the prefix, false otherwise.
*/
function str_starts_with(string $haystack, string $needle): bool
{
$pattern = '/^' . preg_quote($needle, '/') . '/';
return (bool) preg_match($pattern, $haystack);
}
}
define('PHP_PROXY_HUNTER', 'true');
if (!defined('JSON_THROW_ON_ERROR')) {
define('JSON_THROW_ON_ERROR', 4194304);
}
// Detect if the system is Windows
$isWin = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
// Get the current PATH
$currentPath = getenv('PATH');
if ($currentPath === false) {
// Set a default PATH value (customize as needed)
$defaultPath = $isWin ? 'C:\Windows\System32' : '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin';
$currentPath = $defaultPath;
// var_dump("Setting default PATH", $currentPath);
}
if ($currentPath) {
// var_dump("original PATH", $currentPath);
// Specify the new directories to add
$paths = [__DIR__ . '/venv/Scripts'];
$PathSeparator = $isWin ? ";" : ":";
$newDirectory = implode($PathSeparator, $paths);
// Combine the current PATH with the new directory
$newPath = $newDirectory . $PathSeparator . $currentPath;
$explodePath = array_filter(array_unique(explode($PathSeparator, $newPath)));
$explodePath = array_map(function ($str) {
// Only apply realpath if the directory exists
$realPath = realpath($str);
if ($realPath === false) {
return $str;
}
return $realPath;
}, $explodePath);
// Additional logging for debugging
// var_dump("Directories before filtering", $explodePath);
$newPath = implode($PathSeparator, $explodePath);
// Add the new directory to the PATH
putenv("PATH=$newPath");
// Verify the change
// $updatedPath = getenv('PATH');
// var_dump("modified PATH", $updatedPath);
// $output = shell_exec("echo %PATH%");
// echo $output;
// exit;
}
/**
* is debug indicator
* @return bool
*/
function is_debug(): bool
{
$isGitHubCI = getenv('CI') !== false && getenv('GITHUB_ACTIONS') === 'true';
$isGitHubCodespaces = getenv('CODESPACES') === 'true';
if ($isGitHubCI || $isGitHubCodespaces) {
return true;
}
// my device lists
$debug_pc = ['DESKTOP-JVTSJ6I'];
$hostname = gethostname();
if (str_starts_with($hostname, 'codespaces-')) {
return true;
}
return in_array(gethostname(), $debug_pc);
}
// Detect admin
$isAdmin = is_debug();
if (!$isAdmin) {
if ($isCli) {
$short_opts = "p::m::";
$long_opts = [
"proxy::",
"max::",
"userId::",
"lockFile::",
"runner::",
"admin::"
];
$options = getopt($short_opts, $long_opts);
$isAdmin = !empty($options['admin']) && $options['admin'] !== 'false';
}
}
// debug all errors
$enable_debug = $isAdmin;
if ($enable_debug) {
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
} else {
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
}
ini_set("log_errors", 1); // Enable error logging
$error_file = __DIR__ . "/tmp/php-error.txt";
if (!$isCli) {
// Sanitize the user agent string
$user_agent = preg_replace('/[^a-zA-Z0-9-_\.]/', '_', $_SERVER['HTTP_USER_AGENT']);
// Check if the sanitized user agent is empty
if (empty($user_agent)) {
$error_file = __DIR__ . "/tmp/php-error.txt";
} else {
$error_file = __DIR__ . "/tmp/php-error-" . $user_agent . ".txt";
}
}
ini_set("error_log", $error_file); // set error path
if ($enable_debug) {
error_reporting(E_ALL);
} else {
error_reporting(E_ERROR | E_PARSE | E_CORE_ERROR | E_COMPILE_ERROR);
}
// set default timezone
date_default_timezone_set('Asia/Jakarta');
// allocate memory
ini_set('memory_limit', '128M');
// ignore limitation if exists
if (function_exists('set_time_limit')) {
call_user_func('set_time_limit', 0);
}
require_once __DIR__ . '/vendor/autoload.php';
use PhpProxyHunter\ProxyDB;
use PhpProxyHunter\Session;
$dotenv = \Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->safeLoad();
$db = new ProxyDB();
// keep running when user closed the connection (true)
// ignore_user_abort(true);
// ignore user abort execution to false
if (function_exists('ignore_user_abort')) {
call_user_func('ignore_user_abort', false);
}
// start session
if (!$isCli) {
/** @noinspection PhpUnhandledExceptionInspection */
new Session(100 * 3600, __DIR__ . '/tmp/sessions');
// web server admin
$isAdmin = !empty($_SESSION['admin']) && $_SESSION['admin'] === true;
}
// Define $argv for web server context
$argv = isset($argv) ? $argv : [];
/**
* Get project temp folder.
*
* @return string
*/
function tmp(): string
{
$tmpDir = __DIR__ . '/tmp';
// Create temp folder if it doesn't exist
if (!file_exists($tmpDir)) {
if (!mkdir($tmpDir, 0777, true)) {
error_log("Failed to create directory: $tmpDir");
return '';
}
}
// Set permissions for the directory
if (!chmod($tmpDir, 0777)) {
error_log("Failed to set permissions for directory: $tmpDir");
return '';
}
return $tmpDir;
}
/**
* Returns an array of unique objects from the provided array based on a specific property.
*
* @param array $array An array of objects
* @param string $property The property name to compare
* @return array An array of unique objects
*/
function uniqueClassObjectsByProperty(array $array, string $property): array
{
$tempArray = [];
$result = [];
foreach ($array as $item) {
if (property_exists($item, $property)) {
$value = $item->$property;
if (!isset($tempArray[$value])) {
$tempArray[$value] = true;
$result[] = $item;
}
}
}
return $result;
}
/**
* Create parent folders for a file path if they don't exist.
*
* @param string $filePath The file path for which to create parent folders.
*
* @return bool True if all parent folders were created successfully or already exist, false otherwise.
*/
function createParentFolders(string $filePath): bool
{
$parentDir = dirname($filePath);
// Check if the parent directory already exists
if (!is_dir($parentDir)) {
// Attempt to create the parent directory and any necessary intermediate directories
if (!mkdir($parentDir, 0777, true)) {
// Failed to create the directory
error_log("Failed to create directory: $parentDir");
return false;
}
// Set permissions for the parent directory
if (!chmod($parentDir, 0777)) {
error_log("Failed to set permissions for directory: $parentDir");
return false;
}
}
return true;
}
/**
* Sets file permissions to 777 if the file exists.
*
* @param string|array $filenames The filename(s) to set permissions for.
* Can be a single filename or an array of filenames.
* @param bool $autoCreate (optional) Whether to automatically create the file if it doesn't exist. Default is false.
*
* @return void
*/
function setMultiPermissions($filenames, bool $autoCreate = false)
{
if (is_array($filenames)) {
foreach ($filenames as $filename) {
setPermissions($filename, $autoCreate);
}
} elseif (is_string($filenames)) {
setPermissions($filenames, $autoCreate);
} else {
echo "Invalid parameter type. Expected string or array.\n";
}
}
/**
* Sets file permissions to 777 if the file exists.
*
* @param string $filename The filename to set permissions for.
* @param bool $autoCreate (optional) Whether to automatically create the file if it doesn't exist. Default is false.
*
* @return bool Returns true if the permissions were successfully set, false otherwise.
*/
function setPermissions(string $filename, bool $autoCreate = false): bool
{
try {
if (!file_exists($filename) && $autoCreate) {
write_file($filename, '');
}
if (file_exists($filename) && is_readable($filename) && is_writable($filename)) {
return chmod($filename, 0777);
}
} catch (Throwable $th) {
return false;
}
return false;
}
/**
* Checks if a given string is base64 encoded.
*
* @param string|null $string The string to check.
* @return bool True if the string is base64 encoded, false otherwise.
*/
function isBase64Encoded(?string $string): bool
{
if (empty($string)) {
return false;
}
// Check if the string matches the base64 format
if (preg_match('/^[a-zA-Z0-9\/\r\n+]*={0,2}$/', $string)) {
// Decode the string and then re-encode it
$decoded = base64_decode($string, true);
if ($decoded !== false) {
// Compare the re-encoded string to the original
if (base64_encode($decoded) === $string) {
return true;
}
}
}
return false;
}
/**
* Remove specified string from source file and move it to destination file.
*
* This function reads the source file line by line, removes the specified string,
* and writes the modified content back to the source file. It also appends the removed
* string to the destination file.
*
* @param string $sourceFilePath Path to the source file.
* @param string $destinationFilePath Path to the destination file.
* @param string|null $stringToRemove The string to remove from the source file.
* @return string Message indicating success or failure.
*/
function removeStringAndMoveToFile(string $sourceFilePath, string $destinationFilePath, ?string $stringToRemove): string
{
if (!file_exists($destinationFilePath)) {
file_put_contents($destinationFilePath, '');
}
// Check if $stringToRemove is empty or contains only whitespace characters
if (is_null($stringToRemove) || empty(trim($stringToRemove))) {
return "Empty string to remove";
}
// Check if source file is writable
if (!is_writable($sourceFilePath)) {
return "$sourceFilePath not writable";
}
// Check if destination file is writable
if (!is_writable($destinationFilePath)) {
return "$destinationFilePath not writable";
}
// Check if source file is locked
if (is_file_locked($sourceFilePath)) {
return "$sourceFilePath locked";
}
// Check if destination file is locked
if (is_file_locked($destinationFilePath)) {
return "$destinationFilePath locked";
}
// Open source file for reading
$sourceHandle = @fopen($sourceFilePath, 'r');
if (!$sourceHandle) {
return "Failed to open source file";
}
// Open destination file for appending
$destinationHandle = @fopen($destinationFilePath, 'a');
if (!$destinationHandle) {
fclose($sourceHandle);
return "Failed to open destination file";
}
// Open a temporary file for writing
$tempFilePath = tempnam(sys_get_temp_dir(), 'source_temp');
$tempHandle = @fopen($tempFilePath, 'w');
if (!$tempHandle) {
fclose($sourceHandle);
fclose($destinationHandle);
return "Failed to create temporary file";
}
// Acquire an exclusive lock on the source file
if (flock($sourceHandle, LOCK_SH)) {
// Iterate through each line in the source file
while (($line = fgets($sourceHandle)) !== false) {
// Remove the string from the current line
$modifiedLine = str_replace($stringToRemove, '', $line);
// Write the modified line to the temporary file
fwrite($tempHandle, $modifiedLine);
}
// Close file handles
flock($sourceHandle, LOCK_UN);
fclose($sourceHandle);
fclose($tempHandle);
fclose($destinationHandle);
// Replace the source file with the temporary file
if (!rename($tempFilePath, $sourceFilePath)) {
unlink($tempFilePath);
return "Failed to replace source file";
}
// Append the removed string to the destination file
if (file_put_contents($destinationFilePath, PHP_EOL . $stringToRemove . PHP_EOL, FILE_APPEND) === false) {
return "Failed to append removed string to destination file";
}
return "Success";
} else {
fclose($sourceHandle);
fclose($destinationHandle);
fclose($tempHandle);
unlink($tempFilePath);
return "Failed to acquire lock on source file";
}
}
/**
* get cache file from `curlGetWithProxy`
*/
function curlGetCache($url): string
{
return __DIR__ . '/.cache/' . md5($url);
}
/**
* Fetches the content of a URL using cURL with a specified proxy, with caching support.
*
* @param string $url The URL to fetch.
* @param string|null $proxy The proxy IP address and port (e.g., "proxy_ip:proxy_port").
* @param string|null $proxyType The type of proxy. Can be 'http', 'socks4', or 'socks5'. Defaults to 'http'.
* @param float|int $cacheTime The cache expiration time in seconds. Set to 0 to disable caching. Defaults to 1 year (86400 * 360 seconds).
* @param string $cacheDir The directory where cached responses will be stored. Defaults to './.cache/' in the current directory.
* @return string|false The response content or false on failure.
*/
function curlGetWithProxy(string $url, string $proxy = null, ?string $proxyType = 'http', $cacheTime = 86400 * 360, string $cacheDir = __DIR__ . '/.cache/')
{
// Generate cache file path based on URL
if (!file_exists($cacheDir)) {
mkdir($cacheDir);
}
$cacheFile = $cacheDir . md5($url);
// Check if cached data exists and is still valid
if ($cacheTime > 0 && file_exists($cacheFile) && time() - filemtime($cacheFile) < $cacheTime) {
// Return cached response
return read_file($cacheFile);
}
// Initialize cURL session
$ch = buildCurl($proxy, $proxyType, $url);
if ($ch) {
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
}
// Execute the request
$response = curl_exec($ch);
// Check for errors
if (curl_errno($ch)) {
// echo 'Error: ' . curl_error($ch);
} else {
// Save response to cache file
if ($cacheTime > 0) {
write_file($cacheFile, $response);
}
}
// Close cURL session
curl_close($ch);
// Return the response
return $response;
}
/**
* Function to extract IP:PORT combinations from a text file and rewrite the file with only IP:PORT combinations.
*
* @param string $filename The path to the text file.
* @return bool True on success, false on failure.
*/
function rewriteIpPortFile(string $filename): bool
{
if (!file_exists($filename) || !is_readable($filename) || !is_writable($filename)) {
echo "File '$filename' is not readable or writable" . PHP_EOL;
return false;
}
// Open the file for reading
$file = @fopen($filename, "r");
if (!$file) {
echo "Error opening $filename for reading" . PHP_EOL;
return false;
}
// Open a temporary file for writing
$tempFilename = tempnam(__DIR__ . '/tmp', 'rewriteIpPortFile');
$tempFile = @fopen($tempFilename, "w");
if (!$tempFile) {
fclose($file); // Close the original file
echo "Error opening temporary ($tempFilename) file for writing";
return false;
}
// Read each line from the file and extract IP:PORT combinations
while (($line = fgets($file)) !== false) {
// Match IP:PORT pattern using regular expression
preg_match_all('/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+)/', $line, $matches);
// Write matched IP:PORT combinations to the temporary file
foreach ($matches[0] as $match) {
if (!empty(trim($match))) {
fwrite($tempFile, $match . "\n");
}
}
}
// Close both files
fclose($file);
fclose($tempFile);
// Replace the original file with the temporary file
if (!rename($tempFilename, $filename)) {
echo "Error replacing original file with temporary file";
return false;
}
return true;
}
/**
* Reads a file line by line and returns its content as an array.
*
* @param string $filename The path to the file to be read.
* @return array|false An array containing the lines of the file on success, false on failure.
*/
function readFileLinesToArray(string $filename)
{
// Check if the file exists and is readable
if (!is_readable($filename)) {
return false;
}
$lines = [];
// Open the file for reading
$file = @fopen($filename, 'r');
// Read each line until the end of the file
while (!feof($file)) {
// Read the line
$line = fgets($file);
// Add the line to the array
$lines[] = $line;
}
// Close the file
fclose($file);
return $lines;
}
/**
* Get all files with a specific extension in a folder.
*
* @param string $folder The folder path to search for files.
* @param string|null $extension The file extension to filter files by.
*
* @return array An array containing full paths of files with the specified extension.
*/
function getFilesByExtension(string $folder, ?string $extension = 'txt'): array
{
if (!file_exists($folder)) {
echo "$folder not exist" . PHP_EOL;
return [];
}
$files = [];
$folder = rtrim($folder, '/') . '/'; // Ensure folder path ends with a slash
// Open the directory
if ($handle = opendir($folder)) {
// Loop through directory contents
while (false !== ($entry = readdir($handle))) {
$file = $folder . $entry;
// ensure it's a file
if ($entry != "." && $entry != ".." && is_file($file)) {
if (!empty($extension)) {
// Check if file has the specified extension
if (pathinfo($file, PATHINFO_EXTENSION) === $extension) {
$files[] = realpath($file);
}
}
}
}
closedir($handle);
} else {
echo "cannot open $folder\n";
}
return $files;
}
/**
* Check if a given date string in RFC3339 format is older than the specified number of hours.
*
* @param string $dateString The date string in DATE_RFC3339 format.
* @param int $hoursAgo The number of hours to compare against.
* @return bool True if the date is older than the specified number of hours, false otherwise.
*/
function isDateRFC3339OlderThanHours(string $dateString, int $hoursAgo = 5): bool
{
try {
// Create a DateTime object from the string
$date = new DateTime($dateString);
} catch (Exception $e) {
// Handle exception if DateTime creation fails
return false;
}
try {
// Create a DateTime object representing the specified number of hours ago
$hoursAgoDateTime = new DateTime();
$hoursAgoDateTime->sub(new DateInterval('PT' . $hoursAgo . 'H'));
} catch (Exception $e) {
// Handle exception if DateTime creation fails
return false;
}
// Compare the date with the specified number of hours ago
return $date < $hoursAgoDateTime;
}
// Function to parse command line arguments
function parseArgs($args): array
{
$parsedArgs = [];
foreach ($args as $arg) {
if (substr($arg, 0, 2) === '--') {
// Argument is in the format --key=value
$parts = explode('=', substr($arg, 2), 2);
$key = $parts[0];
$value = $parts[1] ?? true; // If value is not provided, set it to true
$parsedArgs[$key] = $value;
}
}
return $parsedArgs;
}
$user_id = "CLI";
if (!$isCli) {
$user_id = md5($_SESSION['user_id'] ?? session_id());
} else {
$parsedArgs = parseArgs($argv);
if (isset($parsedArgs['userId']) && !empty(trim($parsedArgs['userId']))) {
$user_id = trim($parsedArgs['userId']);
}
}
setUserId($user_id);
function setUserId(string $new_user_id)
{
global $user_id;
$user_file = !empty($new_user_id) ? getUserFile($new_user_id) : null;
if ($user_file != null) {
if (!file_exists(dirname($user_file))) {
mkdir(dirname($user_file), 0777, true);
}
// write default user config
if (!file_exists($user_file)) {
$headers = [
'X-Dynatrace: MT_3_6_2809532683_30-0_24d94a15-af8c-49e7-96a0-1ddb48909564_0_1_619',
'X-Api-Key: vT8tINqHaOxXbGE7eOWAhA==',
'Authorization: Bearer',
'X-Request-Id: 63337f4c-ec03-4eb8-8caa-4b7cd66337e3',
'X-Request-At: 2024-04-07T20:57:14.73+07:00',
'X-Version-App: 5.8.8',
'User-Agent: myXL / 5.8.8(741); StandAloneInstall; (samsung; SM-G955N; SDK 25; Android 7.1.2)',
'Content-Type: application/json; charset=utf-8'
];
$data = [
'endpoint' => $new_user_id == 'CLI' ? 'https://api.myxl.xlaxiata.co.id/api/v1/xl-stores/options/list' : 'https://bing.com',
'headers' => $new_user_id == 'CLI' ? $headers : ['User-Agent: Mozilla/5.0 (Linux; Android 14; Pixel 6 Pro Build/UPB3.230519.014) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/114.0.5735.60 Mobile Safari/537.36 GNews Android/2022137898'],
'type' => 'http|socks4|socks5'
];
$file = getUserFile($new_user_id);
write_file($file, json_encode($data));
}
// replace global user id
if ($user_id != $new_user_id) {
$user_id = $new_user_id;
}
}
}
function getUserId(): string
{
global $user_id;
return $user_id;
}
if (!file_exists(__DIR__ . "/config")) {
mkdir(__DIR__ . "/config");
}
setMultiPermissions(__DIR__ . "/config");
function getUserFile(string $user_id): string
{
return __DIR__ . "/config/$user_id.json";
}
function getConfig(string $user_id): array
{
$user_file = getUserFile($user_id);
if (!file_exists($user_file)) {
setUserId($user_id);
$user_file = getUserFile($user_id);
}
// Read the JSON file into a string
$jsonString = read_file($user_file);
// Decode the JSON string into a PHP array
$data = json_decode($jsonString, true); // Use true for associative array, false or omit for object
$defaults = [
'endpoint' => 'https://google.com',
'headers' => [],
'type' => 'http|socks4|socks5',
'user_id' => $user_id
];
// Check if decoding was successful
if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
// Decoding failed
// echo 'Error decoding JSON: ' . json_last_error_msg();
return $defaults;
} else {
return mergeArrays($defaults, $data);
}
}
function setConfig($user_id, $data): array
{
$user_file = getUserFile($user_id);
$defaults = getConfig($user_id);
// remove conflict data
unset($defaults['headers']);
// Encode the data to JSON format
$nData = mergeArrays($defaults, $data);
$newData = json_encode($nData);
// write data
file_put_contents($user_file, $newData);
// set permission
setMultiPermissions($user_file);
return $nData;
}
/**
* Anonymize an email address by masking the username.
*
* @param string $email The email address to anonymize.
* @return string The anonymized email address.
*/
function anonymizeEmail(string $email): string
{
// Split the email into username and domain
list($username, $domain) = explode('@', $email);
// Anonymize the username (keep only the first and the last character)
$username_anon = substr($username, 0, 1) . str_repeat('*', strlen($username) - 2) . substr($username, -1);
// Reconstruct the anonymized email
return $username_anon . '@' . $domain;
}
/**
* Parse incoming POST request data based on Content-Type.
*
* @return array The parsed POST data or null if unsupported content type or parsing fails.
*/
function parsePostData(): array
{
// Get the Content-Type header of the request
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if (strpos($contentType, "multipart/form-data") !== false) {
// Initialize an empty array to store the parsed data
$post_data = [];
// Handle POST fields
foreach ($_POST as $key => $value) {
$post_data[$key] = filter_input(INPUT_POST, $key);
}
// Handle uploaded files
foreach ($_FILES as $key => $file) {
$post_data[$key] = $file;
}
return $post_data;
} elseif ($contentType === "application/json") {
// Request data is JSON
$json_data = json_decode(file_get_contents('php://input'), true);
return ($json_data === null) ? null : $json_data;
} elseif ($contentType === "application/x-www-form-urlencoded") {
// Request data is URL encoded
return $_POST;
} else {
// Unsupported content type
// http_response_code(415); // Unsupported Media Type
return [];
}
}
/**
* Get the request parameters either from POST data, GET parameters, or a combination.
*
* @return array The request parameters array.
*/
function parseQueryOrPostBody(): array
{
global $isCli;
if (!$isCli) {
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
return parsePostData();
} elseif ($_SERVER['REQUEST_METHOD'] === 'GET') {
return $_GET;
} else {
return $_REQUEST;
}
}
return [];
}
/**
* Check if output buffering is active.
*
* @return bool Returns true if output buffering is active, false otherwise.
*/
function is_output_buffering_active()
{
return ob_get_length() !== false;
}
function generateRandomString($length = 10): string
{
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
/**
* Iterate over each line in a string, supporting LF, CRLF, and CR line endings.
*
* @param string $string The input string.
* @param callable|bool $shuffle_or_callback If true, shuffle lines; if callable, callback function.
* @param callable|null $callback The callback function to execute for each line.
* @return void
*/
function iterateLines(string $string, $shuffle_or_callback, ?callable $callback = null): void
{
// Normalize all newlines to LF (\n)
$normalizedString = preg_replace('/\r?\n/', "\n", $string);
// Split the string by LF
$lines = explode("\n", $normalizedString);
if (is_callable($shuffle_or_callback)) {
$callback = $shuffle_or_callback;
$shuffleLines = false;
} elseif ($shuffle_or_callback === true) {
$shuffleLines = true;
} else {
$shuffleLines = false;
}
if ($shuffleLines) {
shuffle($lines);
}
// Iterate over each line and execute the callback
foreach ($lines as $index => $line) {
if (trim($line) !== '') { // Skip empty lines
if ($callback !== null) {
$callback($line, $index);
}
}
}
}
/**
* Iterate over multiple big files line by line and execute a callback for each line.
*
* @param array $filePaths Array of file paths to iterate over.
* @param callable|int $callbackOrMax Callback function or maximum number of lines to read.
* @param callable|null $callback Callback function to execute for each line.
*/
function iterateBigFilesLineByLine(array $filePaths, $callbackOrMax = PHP_INT_MAX, ?callable $callback = null)
{
foreach ($filePaths as $filePath) {
if (!file_exists($filePath) || !is_readable($filePath)) {
print("$filePath not found" . PHP_EOL);
continue;
}
// Create a temporary file to copy the original file content
$tempFile = tmpfile();
$sourceFile = @fopen($filePath, 'r');
if ($sourceFile && $tempFile) {
// Copy content from source file to temporary file
while (($line = fgets($sourceFile)) !== false) {
fwrite($tempFile, $line);
}
// Rewind the temporary file pointer
rewind($tempFile);
// Acquire an exclusive lock on the temporary file
if (flock($tempFile, LOCK_SH)) {
$maxLines = is_callable($callbackOrMax) ? PHP_INT_MAX : $callbackOrMax;
$linesRead = 0;
while (($line = fgets($tempFile)) !== false && $linesRead < $maxLines) {
// skip empty line
if (empty(trim($line))) {
continue;
}
// Execute callback for each line if $callbackOrMax is a callback
if (is_callable($callbackOrMax)) {
call_user_func($callbackOrMax, $line);
} elseif (is_callable($callback)) {
// Execute callback for each line if $callback is provided
call_user_func($callback, $line);
}
$linesRead++;
}
// Release the lock and close the temporary file
flock($tempFile, LOCK_UN);
fclose($tempFile);
} else {
echo "Failed to acquire lock for temporary file" . PHP_EOL;
}
fclose($sourceFile);
} else {
echo "Failed to open $filePath or create temporary file" . PHP_EOL;
}
}
}
/**
* Remove duplicated lines from source file that exist in destination file.
*
* This function reads the contents of two text files line by line. If a line
* from the source file exists in the destination file, it will be removed
* from the source file.
*
* @param string $sourceFile Path to the source text file.
* @param string $destinationFile Path to the destination text file.
* @return bool True if operation is successful, false otherwise.
*/
function removeDuplicateLinesFromSource(string $sourceFile, string $destinationFile): bool
{
// Open source file for reading
$sourceHandle = @fopen($sourceFile, "r");
if (!$sourceHandle) {
return false; // Unable to open source file
}
// Open destination file for reading
$destinationHandle = @fopen($destinationFile, "r");