Repository navigation
Expand file tree
/
Copy pathscan.php
More file actions
1463 lines (1366 loc) · 59.8 KB
/
Copy pathscan.php
File metadata and controls
1463 lines (1366 loc) · 59.8 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
/**
* Universal file scanning script.
*
* Main settings:
* 1) ACCESS_BITRIX - set true to use Bitrix admin authorization; if Bitrix is not detected, password mode is used automatically.
* 2) ACCESS_PASSWORD - password to access the script when not using Bitrix.
* 3) CHUNK_SIZE - how many files to read per AJAX request (chunk).
* 4) SKIP_SYMLINKS - whether to skip symbolic links.
* 5) excludePrefixes - skip files/folders starting with these prefixes.
* 6) excludeFiles - files to skip.
* 7) excludeDirs - directories to skip.
* 8) DEBUG_MODE - enable detailed debug logging.
*/
// -------------------------------------
// 1. Configuration
// -------------------------------------
define('CHUNK_SIZE', 10); // How many files to read per AJAX request (chunk)
define('ACCESS_BITRIX', true); // Set true for admin-only access, false for password login (auto-disables if Bitrix not detected)
define('ACCESS_PASSWORD', '123456'); // Password to access the script (if not using Bitrix)
define('TOKEN_MAX', '800000'); // Maximum token count per file (to limit size)
$SKIP_SYMLINKS = false;
// Exclusions
$excludePrefixes = ['_', 'test']; // Files/folders starting with these prefixes are skipped
$excludeFiles = ['composer.lock'];
$excludeDirs = ['log', 'vendor', 'old'];
// Enable detailed debug log?
define('DEBUG_MODE', false); // Set to true for more details
// Determine Bitrix availability and access mode
$docRoot = realpath($_SERVER['DOCUMENT_ROOT']);
$bitrixPrologPath = $docRoot ? $docRoot . '/bitrix/modules/main/include/prolog_before.php' : '';
$useBitrix = (defined('ACCESS_BITRIX') && ACCESS_BITRIX === true && $bitrixPrologPath && file_exists($bitrixPrologPath));
// -------------------------------------
// 0. If running in Bitrix mode, connect the core first
// -------------------------------------
if ($useBitrix) {
require_once $bitrixPrologPath;
global $USER;
// Exit if not an admin
if (!$USER->IsAdmin()) {
header("HTTP/1.1 403 Forbidden");
echo "Access denied";
exit;
}
}
// -------------------------------------
// 1. Start the session (after prolog_before)
// -------------------------------------
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Holds warning text for password mode (not used when default password is blocked)
$passwordWarning = '';
// -------------------------------------
// 2. If not in Bitrix mode, check the password
// -------------------------------------
if (!$useBitrix) {
if (ACCESS_PASSWORD === '123456') {
renderDefaultPasswordWarning();
}
if (empty($_SESSION['scan2json_authenticated']) || $_SESSION['scan2json_authenticated'] !== true) {
$errorMessage = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$password = $_POST['access_password'] ?? '';
if ($password === ACCESS_PASSWORD) {
$_SESSION['scan2json_authenticated'] = true;
header('Location: ' . $_SERVER['PHP_SELF']);
exit;
}
$errorMessage = 'Invalid password.';
}
renderPasswordForm($errorMessage);
}
}
// Make sure the session has required variables
if (!isset($_SESSION['SCAN_TMPFILE'])) $_SESSION['SCAN_TMPFILE'] = '';
if (!isset($_SESSION['SCAN_FILECOUNT']))$_SESSION['SCAN_FILECOUNT'] = 0;
if (!isset($_SESSION['SCAN_OFFSET'])) $_SESSION['SCAN_OFFSET'] = 0;
if (!isset($_SESSION['CUR_FOLDER'])) $_SESSION['CUR_FOLDER'] = '';
// -------------------------------------
// 3. Global debug log (if needed)
// -------------------------------------
$GLOBALS['DEBUG_LOG'] = [];
function debugLog($msg) {
if (DEBUG_MODE) {
$GLOBALS['DEBUG_LOG'][] = $msg;
}
}
/**
* Renders a Bootstrap-based password login page and exits.
*
* @param string|null $errorMessage Optional error message to display above the form.
* @return void
*/
function renderPasswordForm(?string $errorMessage = null): void
{
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Access required</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-5">
<div class="row justify-content-center">
<div class="col-md-4">
<div class="card shadow-sm">
<div class="card-body">
<h1 class="h4 mb-3 text-center">Enter password</h1>
<?php if ($errorMessage !== null): ?>
<div class="alert alert-danger py-2 mb-3">
<?=htmlspecialchars($errorMessage, ENT_QUOTES, 'UTF-8')?>
</div>
<?php endif; ?>
<form method="post">
<div class="mb-3">
<label for="access_password" class="form-label">Password</label>
<input
type="password"
name="access_password"
id="access_password"
class="form-control"
autocomplete="current-password"
required
>
</div>
<button type="submit" class="btn btn-primary w-100">Log in</button>
</form>
</div>
</div>
<p class="text-muted small mt-3 text-center">
Tip: change the ACCESS_PASSWORD constant in the script before using it on a real server.
</p>
</div>
</div>
</div>
</body>
</html>
<?php
exit;
}
/**
* Renders a blocking notice when the default password is still in use.
*
* @return void
*/
function renderDefaultPasswordWarning(): void
{
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Access blocked</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-5">
<div class="row justify-content-center">
<div class="col-md-5">
<div class="card shadow-sm border-danger">
<div class="card-body">
<h1 class="h4 mb-3 text-center text-danger">Access blocked</h1>
<div class="alert alert-warning mb-0">
Please change the ACCESS_PASSWORD constant from the default value before using this tool.
</div>
</div>
</div>
<p class="text-muted small mt-3 text-center">
Update ACCESS_PASSWORD in scan.php and reload the page.
</p>
</div>
</div>
</div>
</body>
</html>
<?php
exit;
}
/**
* Reset scan-related session state.
*
* @return void
*/
function resetScanState(): void
{
$_SESSION['SCAN_TMPFILE'] = '';
$_SESSION['SCAN_FILECOUNT'] = 0;
$_SESSION['SCAN_OFFSET'] = 0;
$_SESSION['SCAN_JSONLFILE'] = '';
$_SESSION['SCAN_JSONFILE'] = '';
$_SESSION['SCAN_FOLDERNAME'] = '';
}
/**
* Decode custom selection JSON and return allowed top-level items.
*
* @param string $raw
* @return array<string>
*/
function parseCustomSelection(string $raw): array
{
if ($raw === '') {
return [];
}
$decoded = json_decode($raw, true);
if (!is_array($decoded) || !isset($decoded['items']) || !is_array($decoded['items'])) {
return [];
}
$clean = [];
foreach ($decoded['items'] as $item) {
if (is_string($item) && $item !== '') {
$clean[] = $item;
}
}
return $clean;
}
/**
* Recursively clear files and subdirectories inside scan_tmp.
*
* @param string $dir
* @return array<string, int> Array with deleted and errors counters.
*/
function clearScanTmp(string $dir): array
{
$deleted = 0;
$errors = 0;
if (!is_dir($dir)) {
return ['deleted' => 0, 'errors' => 0];
}
$items = @scandir($dir);
if (!is_array($items)) {
return ['deleted' => 0, 'errors' => 1];
}
foreach ($items as $item) {
if ($item === '.' || $item === '..') {
continue;
}
$path = $dir . '/' . $item;
if (is_dir($path)) {
$result = clearScanTmp($path);
$deleted += $result['deleted'];
$errors += $result['errors'];
if (@rmdir($path)) {
$deleted++;
} else {
$errors++;
}
} else {
if (@unlink($path)) {
$deleted++;
} else {
$errors++;
}
}
}
return ['deleted' => $deleted, 'errors' => $errors];
}
/**
* Check if scan_tmp contains any files or folders.
*
* @param string $dir
* @return bool
*/
function scanTmpHasData(string $dir): bool
{
if (!is_dir($dir)) {
return false;
}
$items = @scandir($dir);
if (!is_array($items)) {
return false;
}
foreach ($items as $item) {
if ($item !== '.' && $item !== '..') {
return true;
}
}
return false;
}
/**
* Convert bytes to a short human-readable string (e.g., 950B, 1.2KB, 12MB).
*
* @param int $bytes
* @return string
*/
function formatSize(int $bytes): string
{
$units = ['B', 'KB', 'MB', 'GB', 'TB'];
$i = 0;
$size = $bytes;
while ($size >= 1024 && $i < count($units) - 1) {
$size /= 1024;
$i++;
}
if ($size >= 100) {
$sizeStr = (string) round($size);
} elseif ($size >= 10) {
$sizeStr = number_format($size, 1);
} else {
$sizeStr = number_format($size, 2);
}
return $sizeStr . $units[$i];
}
// -------------------------------------
// 4. AJAX: handle one chunk (scanChunk)
// -------------------------------------
if (
isset($_REQUEST['ajax']) && $_REQUEST['ajax'] === 'Y'
&& isset($_REQUEST['action']) && $_REQUEST['action'] === 'scanChunk'
) {
// Return JSON only
header('Content-Type: application/json; charset=UTF-8');
$tmpFile = $_SESSION['SCAN_TMPFILE'] ?? '';
$total = (int) ($_SESSION['SCAN_FILECOUNT'] ?? 0);
$offset = (int) ($_SESSION['SCAN_OFFSET'] ?? 0);
// New: path to the jsonl file and json file
$jsonlFile = '';
$jsonFile = '';
if ($tmpFile) {
$jsonlFile = preg_replace('/\.txt$/', '.jsonl', $tmpFile);
$jsonFile = preg_replace('/\.txt$/', '.json', $tmpFile);
if (!isset($_SESSION['SCAN_JSONLFILE'])) {
$_SESSION['SCAN_JSONLFILE'] = $jsonlFile;
}
if (!isset($_SESSION['SCAN_JSONFILE'])) {
$_SESSION['SCAN_JSONFILE'] = $jsonFile;
}
}
// If the file list is not built
if (!$tmpFile || !file_exists($tmpFile) || $total <= 0) {
echo json_encode([
'status' => 'error',
'message' => 'File list is not initialized or is empty.'
]);
exit;
}
// Function to check for binary files
function isBinaryFile($path) {
$h = @fopen($path, 'rb');
if (!$h) return true; // if open failed, treat as binary to skip it
$chunk = fread($h, 1024);
fclose($h);
return (strpos($chunk, "\0") !== false);
}
// Read N lines from file starting at byte offset
function readPathsChunk($filePath, $byteOffset, $count) {
$paths = [];
$h = fopen($filePath, 'rb');
fseek($h, $byteOffset);
$readLines = 0;
while (!feof($h) && $readLines < $count) {
$line = fgets($h);
if ($line === false) break;
$line = trim($line);
if ($line !== '') {
$paths[] = $line;
$readLines++;
}
}
$newOffset = ftell($h);
fclose($h);
return [$paths, $newOffset];
}
// Read a chunk of paths
list($paths, $newOffset) = readPathsChunk($tmpFile, $offset, CHUNK_SIZE);
if (empty($paths)) {
// Count tokens in the jsonl file
$tokenCount = 0;
$jsonlFilePath = $_SESSION['SCAN_JSONLFILE'] ?? '';
if ($jsonlFilePath && file_exists($jsonlFilePath)) {
$fh = fopen($jsonlFilePath, 'rb');
while (($line = fgets($fh)) !== false) {
$row = json_decode($line, true);
if (isset($row['content'])) {
$tokenCount += str_word_count($row['content']);
}
}
fclose($fh);
}
// Build JSON files in parts
$jsonFilePath = $_SESSION['SCAN_JSONFILE'] ?? '';
$jsonParts = [];
$jsonPartFiles = [];
$folderName = $_SESSION['SCAN_FOLDERNAME'] ?? 'result';
$safeFolder = preg_replace('/[^a-zA-Z0-9_\-]+/u', '_', $folderName);
$tokenMax = (int)constant('TOKEN_MAX');
$zipFile = '';
$jsonlSize = '';
$jsonSize = '';
$jsonlZipSize = '';
$jsonZipSize = '';
$partsZipSize = '';
$jsonFileCreated = false;
$jsonlZipFile = '';
$jsonZipFile = '';
$splitMode = false;
if ($jsonlFilePath && file_exists($jsonlFilePath) && $jsonFilePath) {
$fh = fopen($jsonlFilePath, 'rb');
$jsonHandle = @fopen($jsonFilePath, 'wb');
$firstJsonItem = true;
if ($jsonHandle) {
fwrite($jsonHandle, "[\n");
}
$currentPart = [];
$currentTokens = 0;
$partNum = 1;
$baseName = basename($jsonFilePath, '.json');
while (($line = fgets($fh)) !== false) {
$row = json_decode($line, true);
if (!$row) continue;
$tokens = isset($row['content']) ? str_word_count($row['content']) : 0;
// Stream to the single JSON file as an array
if ($jsonHandle) {
$encoded = json_encode($row, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
if ($encoded !== false) {
if (!$firstJsonItem) {
fwrite($jsonHandle, ",\n");
}
fwrite($jsonHandle, $encoded);
$firstJsonItem = false;
}
}
// If adding the line exceeds the limit, save the part and start a new one
if ($currentTokens + $tokens > $tokenMax && count($currentPart) > 0) {
$splitMode = true;
$partFile = dirname($jsonFilePath) . '/' . $baseName . '_' . $partNum . '.json';
file_put_contents($partFile, json_encode($currentPart, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
$jsonPartFiles[] = basename($partFile);
$partNum++;
$currentPart = [];
$currentTokens = 0;
}
$currentPart[] = $row;
$currentTokens += $tokens;
}
fclose($fh);
if ($jsonHandle) {
fwrite($jsonHandle, "\n]");
fclose($jsonHandle);
$jsonFileCreated = true;
}
// Save the last part only if we actually split
if ($splitMode && count($currentPart) > 0) {
$partFile = dirname($jsonFilePath) . '/' . $baseName . '_' . $partNum . '.json';
file_put_contents($partFile, json_encode($currentPart, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
$jsonPartFiles[] = basename($partFile);
}
// Normalize part numbering with padding
if ($splitMode && count($jsonPartFiles) > 0) {
$totalParts = count($jsonPartFiles);
$pad = strlen((string)$totalParts);
$renamedParts = [];
foreach ($jsonPartFiles as $idx => $fname) {
$newName = $baseName . '_' . str_pad($idx + 1, $pad, '0', STR_PAD_LEFT) . '.json';
$oldPath = dirname($jsonFilePath) . '/' . $fname;
$newPath = dirname($jsonFilePath) . '/' . $newName;
if ($newPath !== $oldPath) {
@rename($oldPath, $newPath);
}
$renamedParts[] = $newName;
}
$jsonPartFiles = $renamedParts;
}
// Archive all parts into a zip
if ($splitMode && count($jsonPartFiles) > 0) {
$zipFile = dirname($jsonFilePath) . '/' . $baseName . '_parts.zip';
$zip = new ZipArchive();
if ($zip->open($zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
foreach ($jsonPartFiles as $f) {
$zip->addFile(dirname($jsonFilePath) . '/' . $f, $f);
}
$zip->close();
} else {
$zipFile = '';
}
}
// Zip JSONL
if (file_exists($jsonlFilePath)) {
$jsonlBase = basename($jsonlFilePath, '.jsonl');
$jsonlZipPath = dirname($jsonlFilePath) . '/' . $jsonlBase . '.jsonl.zip';
$zip = new ZipArchive();
if ($zip->open($jsonlZipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
$zip->addFile($jsonlFilePath, basename($jsonlFilePath));
$zip->close();
$jsonlZipFile = basename($jsonlZipPath);
$jsonlZipSize = file_exists($jsonlZipPath) ? formatSize((int) filesize($jsonlZipPath)) : '';
}
$jsonlSize = formatSize((int) filesize($jsonlFilePath));
}
// Zip single JSON (if created)
if ($jsonFileCreated && file_exists($jsonFilePath)) {
$jsonBase = basename($jsonFilePath, '.json');
$jsonZipPath = dirname($jsonFilePath) . '/' . $jsonBase . '.json.zip';
$zip = new ZipArchive();
if ($zip->open($jsonZipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
$zip->addFile($jsonFilePath, basename($jsonFilePath));
$zip->close();
$jsonZipFile = basename($jsonZipPath);
}
$jsonSize = formatSize((int) filesize($jsonFilePath));
if (file_exists($jsonZipPath ?? '')) {
$jsonZipSize = formatSize((int) filesize($jsonZipPath));
}
}
if (file_exists($zipFile)) {
$partsZipSize = formatSize((int) filesize($zipFile));
}
}
echo json_encode([
'status' => 'done',
'message' => 'All files processed',
'processed' => 0,
'total' => $total,
'jsonl' => '',
'jsonl_file'=> basename($_SESSION['SCAN_JSONLFILE'] ?? ''),
'json_file' => $jsonFileCreated ? basename($_SESSION['SCAN_JSONFILE'] ?? '') : '',
'json_parts'=> $jsonPartFiles,
'zip_file' => $zipFile ? basename($zipFile) : '',
'jsonl_zip' => $jsonlZipFile,
'json_zip' => $jsonZipFile,
'jsonl_size'=> $jsonlSize,
'json_size' => $jsonSize,
'jsonl_zip_size' => $jsonlZipSize,
'json_zip_size' => $jsonZipSize,
'zip_size' => $partsZipSize,
'token_count' => $tokenCount
]);
$_SESSION['SCAN_OFFSET'] = $newOffset;
exit;
}
// Process paths
$docRoot = realpath($_SERVER['DOCUMENT_ROOT']);
$jsonl = '';
$count = 0;
// Open jsonl file for appending
$jsonlFp = @fopen($jsonlFile, 'ab');
if (!$jsonlFp) {
echo json_encode([
'status' => 'error',
'message' => 'Failed to open file for writing: ' . $jsonlFile
]);
exit;
}
foreach ($paths as $p) {
// Skip binaries
if (isBinaryFile($p)) {
continue;
}
$content = @file_get_contents($p);
if ($content === false) {
continue;
}
// Path relative to document root
$rel = ltrim(str_replace($docRoot, '', $p), '/');
$data = [
'file' => $rel,
'content' => $content
];
$line = json_encode($data, JSON_UNESCAPED_UNICODE)."\n";
fwrite($jsonlFp, $line);
$count++;
}
fclose($jsonlFp);
// Update the offset
$_SESSION['SCAN_OFFSET'] = $newOffset;
// Return result
echo json_encode([
'status' => 'ok',
'processed' => $count,
'total' => $total,
'jsonl' => '',
'jsonl_file'=> basename($jsonlFile),
'json_file' => basename($jsonFile)
// json_parts is not returned on intermediate chunks
]);
exit;
}
// -------------------------------------
// 5. Functions to build the file list
// -------------------------------------
function shouldProcessPath($fullPath, &$visitedInodes) {
global $SKIP_SYMLINKS;
if ($SKIP_SYMLINKS && is_link($fullPath)) {
debugLog("[shouldProcessPath] Skipping symlink: $fullPath");
return false;
}
$inode = @fileinode($fullPath);
// Skip if already seen (and not the symlink itself)
if ($inode && isset($visitedInodes[$inode]) && !is_link($fullPath)) {
debugLog("[shouldProcessPath] Duplicate inode, skipping: $fullPath");
return false;
}
// Mark any non-symlink so we do not enter it again
if ($inode && !is_link($fullPath)) {
$visitedInodes[$inode] = true;
}
return true;
}
/**
* Collect file paths recursively into the temp list.
*
* @param string $dir
* @param resource $fp
* @param array<int, bool> $visitedInodes
* @param array<string> $allowedRootItems
* @param int $depth
* @return void
*/
function collectFilePathsToFile($dir, $fp, &$visitedInodes, array $allowedRootItems, $depth = 0) {
global $excludePrefixes, $excludeFiles, $excludeDirs;
// Get all items in the folder
$items = @scandir($dir);
if ($items === false) {
debugLog("[scandir failed] $dir → " . print_r(error_get_last(), true));
return;
}
if (!is_array($items)) return;
$hasFiles = false;
foreach ($items as $item) {
if ($item === '.' || $item === '..') continue;
if ($depth === 0 && !empty($allowedRootItems) && !in_array($item, $allowedRootItems, true)) {
continue;
}
// Skip folders with the configured prefixes
foreach ($excludePrefixes as $pref) {
if (strpos($item, $pref) === 0) {
continue 2;
}
}
// Full path to file or folder
$full = $dir . '/' . $item;
// Log current item being processed
debugLog("[collectFilePathsToFile] Checking: $full");
if (!shouldProcessPath($full, $visitedInodes)) {
continue;
}
// If this is a folder
if (is_dir($full)) {
if (in_array($item, $excludeDirs)) {
continue;
}
// Recursively handle nested folders
collectFilePathsToFile($full, $fp, $visitedInodes, $allowedRootItems, $depth + 1);
} elseif (is_file($full)) {
// If this is a file, write its path
if (in_array($item, $excludeFiles)) {
continue;
}
fwrite($fp, $full . "\n");
$hasFiles = true;
}
}
if ($hasFiles) {
debugLog("[collectFilePathsToFile] Folder with files: $dir");
} else {
debugLog("[collectFilePathsToFile] Folder is empty: $dir");
}
}
// -------------------------------------
// 6. Form processing
// -------------------------------------
$method = $_POST['folder_select_method'] ?? 'manual';
$currentFolderDropdown = $_SESSION['CUR_FOLDER'] ?? '';
$docRoot = realpath($_SERVER['DOCUMENT_ROOT']);
$scanTmpDir = $docRoot . '/scan_tmp';
$hasGeneratedData = scanTmpHasData($scanTmpDir);
$manualPathInput = ltrim((string)($_POST['scan_folder'] ?? ''), '/');
$customSelectionRaw = $_POST['custom_selection'] ?? '';
$allowedRootItems = parseCustomSelection($customSelectionRaw);
$selectionError = '';
$currentSubdirs = [];
$currentFiles = [];
$openSelection = isset($_POST['open_selection']) && $_POST['open_selection'] === '1';
$clearMessage = '';
// Reset
if (isset($_POST['reset'])) {
resetScanState();
$_SESSION['CUR_FOLDER'] = '';
$currentFolderDropdown = '';
$customSelectionRaw = '';
$allowedRootItems = [];
$selectionError = '';
$hasGeneratedData = scanTmpHasData($scanTmpDir);
}
// Clear generated data in scan_tmp
if (isset($_POST['clear_generated'])) {
$res = clearScanTmp($scanTmpDir);
resetScanState();
$_SESSION['CUR_FOLDER'] = '';
$currentFolderDropdown = '';
$customSelectionRaw = '';
$allowedRootItems = [];
$selectionError = '';
$clearMessage = "Deleted {$res['deleted']} item(s) from scan_tmp" . ($res['errors'] ? " with {$res['errors']} error(s)" : '');
$hasGeneratedData = scanTmpHasData($scanTmpDir);
}
// Expand subfolders
if (
$method === 'dropdown'
&& isset($_POST['expandDropdown'])
&& !isset($_POST['collect_and_scan'])
) {
resetScanState();
$sel = trim($_POST['selected_subfolder'] ?? '', '/');
if ($sel !== '') {
$tryRel = $currentFolderDropdown
? "$currentFolderDropdown/$sel"
: $sel;
$fullTry = $docRoot . '/' . $tryRel;
if (is_dir($fullTry)) {
$_SESSION['CUR_FOLDER'] = $tryRel;
$currentFolderDropdown = $tryRel;
}
}
}
// -------------------------------------
// 7. "Generate and scan"
// -------------------------------------
$scanMessage = '';
if (isset($_POST['collect_and_scan'])) {
$_SESSION['SCAN_TMPFILE'] = '';
$_SESSION['SCAN_FILECOUNT'] = 0;
$_SESSION['SCAN_OFFSET'] = 0;
$_SESSION['SCAN_JSONLFILE'] = '';
$_SESSION['SCAN_FOLDERNAME'] = '';
$docRoot = realpath($_SERVER['DOCUMENT_ROOT']);
$fullPathToScan = '';
$folderName = '';
if ($method === 'manual') {
$input = ltrim($_POST['scan_folder'] ?? '', '/');
$path = $docRoot . '/' . $input;
$folderName = $input !== '' ? basename($input) : 'root';
if (is_dir($path) && is_readable($path)) {
$fullPathToScan = $path;
} else {
$scanMessage = "Folder \"{$path}\" not found or not readable.";
}
} else {
$try = $docRoot . '/' . ltrim($currentFolderDropdown, '/');
$folderName = $currentFolderDropdown !== '' ? basename($currentFolderDropdown) : 'root';
if (is_dir($try)) {
$fullPathToScan = $try;
}
}
// Save folder name in the session
$_SESSION['SCAN_FOLDERNAME'] = $folderName;
if (!$fullPathToScan) {
$scanMessage = "Folder not found or outside of DOCUMENT_ROOT.";
} elseif ($customSelectionRaw !== '' && empty($allowedRootItems)) {
$scanMessage = "Please select at least one item to scan.";
} else {
$tmpDir = $docRoot . '/scan_tmp';
if (!is_dir($tmpDir)) {
@mkdir($tmpDir, 0777, true);
}
// Build file name using folder name and timestamp
$safeFolder = preg_replace('/[^a-zA-Z0-9_\-]+/u', '_', $folderName);
$timestamp = date('ymdHis');
$baseName = $safeFolder . '_' . $timestamp;
$tmpFilePath = $tmpDir . '/' . $baseName . '.txt';
$fp = @fopen($tmpFilePath, 'wb');
if (!$fp) {
$scanMessage = "Failed to create temporary file: $tmpFilePath";
} else {
$visited = [];
collectFilePathsToFile($fullPathToScan, $fp, $visited, $allowedRootItems, 0);
fclose($fp);
// Count lines
$lineCount = 0;
$check = fopen($tmpFilePath, 'rb');
while (!feof($check)) {
$line = fgets($check);
if ($line !== false) $lineCount++;
}
fclose($check);
$_SESSION['SCAN_TMPFILE'] = $tmpFilePath;
$_SESSION['SCAN_FILECOUNT'] = $lineCount;
$_SESSION['SCAN_OFFSET'] = 0;
// json/jsonl files share this base name
$_SESSION['SCAN_JSONLFILE'] = preg_replace('/\.txt$/', '.jsonl', $tmpFilePath);
$_SESSION['SCAN_JSONFILE'] = preg_replace('/\.txt$/', '.json', $tmpFilePath);
$scanMessage = "List prepared. Total files: $lineCount. Starting automatic scanning...";
}
}
}
// Handle the "Level up" button
if (isset($_POST['goUp']) && $currentFolderDropdown) {
// Split current path by "/"
resetScanState();
$parentFolder = dirname($currentFolderDropdown);
$_SESSION['CUR_FOLDER'] = $parentFolder === '/' ? '' : $parentFolder;
$currentFolderDropdown = $_SESSION['CUR_FOLDER']; // Update current folder
}
// Build lists for current folder (subdirs and files)
$listingTarget = $method === 'manual' ? $manualPathInput : $currentFolderDropdown;
$listingPath = $docRoot . '/' . trim($listingTarget, '/');
if (is_dir($listingPath)) {
$items = @scandir($listingPath);
if (is_array($items)) {
foreach ($items as $itm) {
if ($itm === '.' || $itm === '..') {
continue;
}
$full = $listingPath . '/' . $itm;
if (is_dir($full)) {
$currentSubdirs[] = $itm;
} elseif (is_file($full)) {
$currentFiles[] = $itm;
}
}
}
}
sort($currentSubdirs);
sort($currentFiles);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Scanner</title>
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-4">
<h1 class="mb-4">File Scanner</h1>
<?php if ($passwordWarning !== ''): ?>
<div class="alert alert-warning"><?=htmlspecialchars($passwordWarning, ENT_QUOTES, 'UTF-8')?></div>
<?php endif; ?>
<!-- Form -->
<form method="post" action="" class="mb-4" id="scanForm">
<input type="hidden" name="custom_selection" id="custom_selection" value="<?=htmlspecialchars($customSelectionRaw, ENT_QUOTES, 'UTF-8')?>">
<div class="mb-3">
<label class="form-label fw-bold">How to select the folder:</label>
<div class="form-check">
<input
class="form-check-input"
type="radio"
name="folder_select_method"
id="radioManual"
value="manual"
<?php if ($method === 'manual') echo 'checked'; ?>
>
<label class="form-check-label" for="radioManual">
Enter path manually ("/" is the root)
</label>
</div>
<div class="ms-3 mt-2" id="manualBlock" style="display:none;">
<label for="scan_folder" class="form-label">
Examples: "/", "/local", "/catalog/images"
</label>
<div class="d-flex align-items-center gap-2">
<input
type="text"
name="scan_folder"
id="scan_folder"
class="form-control"
value="<?=htmlspecialchars($_POST['scan_folder'] ?? '')?>"
placeholder="Example: /local"
>
<button type="button" class="btn btn-secondary choose-items-btn text-nowrap">Choose items…</button>
</div>
</div>
</div>
<div class="mb-3">
<div class="form-check">
<input
class="form-check-input"
type="radio"
name="folder_select_method"
id="radioDropdown"
value="dropdown"
<?php if ($method === 'dropdown') echo 'checked'; ?>
>
<label class="form-check-label" for="radioDropdown">
Select from list
</label>
</div>
<div class="mt-2" id="dropdownBlock" style="display:none;">
<div class="d-flex align-items-center gap-2 mb-3">
<div class="alert alert-secondary p-2 mb-0 flex-grow-1">
<strong>Current folder:</strong>
<?php if (!$currentFolderDropdown): ?>
Site root
<?php else: ?>
/<?=htmlspecialchars($currentFolderDropdown)?>
<?php endif; ?>
</div>
<button type="button" class="btn btn-secondary choose-items-btn">Choose items…</button>
</div>
<div class="d-flex align-items-center gap-2 mb-3">
<?php
$subfolders = $currentSubdirs;
if (!empty($subfolders)) {
?>
<!-- Automatic submit -->
<input type="hidden" name="expandDropdown" value="1">
<select name="selected_subfolder"
class="form-select w-auto"
onchange="this.form.submit();">
<option value="">-- Select a subfolder --</option>
<?php foreach ($subfolders as $sf): ?>
<option value="<?=htmlspecialchars($sf)?>"><?=$sf?></option>
<?php endforeach; ?>
</select>
<?php
}
?>
<?php if ($currentFolderDropdown): ?>
<button type="submit" name="goUp" class="btn btn-outline-secondary">Go up one level</button>
<button type="submit" name="reset" class="btn btn-outline-danger">Reset path</button>
<?php endif; ?>
</div>
</div>
</div>
<div id="selectionPanel" class="bg-white border rounded p-3 mb-3" style="display:none;">
<h6 class="mb-1">Select folders and files to include in the scan</h6>
<p class="text-muted small mb-3">All items are selected by default. Uncheck those you want to exclude.</p>
<div class="row g-2 mb-3">
<?php