-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfilemanager.php
More file actions
2091 lines (1846 loc) Β· 99.2 KB
/
filemanager.php
File metadata and controls
2091 lines (1846 loc) Β· 99.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
session_start();
// Cross-platform compatibility detection
define('IS_WINDOWS', DIRECTORY_SEPARATOR === '\\');
define('IS_LINUX', !IS_WINDOWS);
// Configuration
define('FM_USERNAME', 'admin');
define('FM_PASSWORD', 'filemanager123');
define('FM_ROOT_PATH', __DIR__);
define('FM_SESSION_TIMEOUT', 3600); // 1 hour
// Database Configuration
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'mysql');
// Linux MySQL socket support (comment out to use TCP)
// define('DB_SOCKET', '/var/run/mysqld/mysqld.sock');
// Security: Disable dangerous functions
if (function_exists('exec')) {
ini_set('disable_functions', 'exec,shell_exec,system,passthru,proc_open,popen');
}
// Database connection with cross-platform support
function getDBConnection() {
try {
// Build DSN with socket support for Linux
$dsn = "mysql:charset=utf8";
if (defined('DB_SOCKET') && IS_LINUX && file_exists(constant('DB_SOCKET'))) {
// Use Unix socket on Linux if available
$dsn .= ";unix_socket=" . constant('DB_SOCKET');
} else {
// Use TCP connection
$dsn .= ";host=" . DB_HOST;
// Add port if specified
if (defined('DB_PORT')) {
$dsn .= ";port=" . constant('DB_PORT');
}
}
$pdo = new PDO($dsn, DB_USERNAME, DB_PASSWORD);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
} catch (PDOException $e) {
error_log("Database connection failed: " . $e->getMessage());
return null;
}
}
// Get databases list
function getDatabases() {
$pdo = getDBConnection();
if (!$pdo) return [];
try {
$stmt = $pdo->query("SHOW DATABASES");
return $stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (PDOException $e) {
return [];
}
}
// Get tables from database with detailed error information
function getTables($database) {
$pdo = getDBConnection();
if (!$pdo) {
return ['error' => 'Database connection failed. Please check your database configuration.'];
}
try {
// Validate database name
if (empty($database)) {
return ['error' => 'No database selected'];
}
// Check if database exists
$stmt = $pdo->query("SHOW DATABASES LIKE " . $pdo->quote($database));
if ($stmt->rowCount() === 0) {
return ['error' => "Database '$database' does not exist"];
}
$pdo->exec("USE `" . str_replace('`', '``', $database) . "`");
$stmt = $pdo->query("SHOW TABLES");
$tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
return ['tables' => $tables, 'count' => count($tables)];
} catch (PDOException $e) {
error_log("getTables error: " . $e->getMessage());
return ['error' => 'Database error: ' . $e->getMessage()];
}
}
// Execute SQL query
function executeQuery($database, $query) {
$pdo = getDBConnection();
if (!$pdo) return ['error' => 'Database connection failed'];
try {
$pdo->exec("USE `$database`");
$stmt = $pdo->prepare($query);
$stmt->execute();
if (stripos(trim($query), 'SELECT') === 0 || stripos(trim($query), 'SHOW') === 0 || stripos(trim($query), 'DESC') === 0) {
return ['data' => $stmt->fetchAll(PDO::FETCH_ASSOC)];
} else {
return ['message' => 'Query executed successfully. Rows affected: ' . $stmt->rowCount()];
}
} catch (PDOException $e) {
return ['error' => $e->getMessage()];
}
}
// Cross-platform path normalization
function normalizePath($path) {
$path = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path);
return rtrim($path, DIRECTORY_SEPARATOR);
}
// Check file/directory permissions (enhanced for Linux)
function checkPermissions($path) {
$permissions = [];
if (!file_exists($path)) {
return ['exists' => false];
}
$permissions['exists'] = true;
$permissions['readable'] = is_readable($path);
$permissions['writable'] = is_writable($path);
$permissions['executable'] = is_executable($path);
if (IS_LINUX) {
// Get detailed Unix permissions
$perms = fileperms($path);
$permissions['octal'] = substr(sprintf('%o', $perms), -3);
$permissions['owner_read'] = ($perms & 0x0100) ? true : false;
$permissions['owner_write'] = ($perms & 0x0080) ? true : false;
$permissions['owner_execute'] = ($perms & 0x0040) ? true : false;
$permissions['group_read'] = ($perms & 0x0020) ? true : false;
$permissions['group_write'] = ($perms & 0x0010) ? true : false;
$permissions['group_execute'] = ($perms & 0x0008) ? true : false;
$permissions['other_read'] = ($perms & 0x0004) ? true : false;
$permissions['other_write'] = ($perms & 0x0002) ? true : false;
$permissions['other_execute'] = ($perms & 0x0001) ? true : false;
// Get owner information if possible
if (function_exists('posix_getpwuid') && function_exists('fileowner')) {
$owner = posix_getpwuid(fileowner($path));
$permissions['owner'] = $owner['name'] ?? 'unknown';
}
if (function_exists('posix_getgrgid') && function_exists('filegroup')) {
$group = posix_getgrgid(filegroup($path));
$permissions['group'] = $group['name'] ?? 'unknown';
}
}
return $permissions;
}
// Enhanced directory tree building with permission checks
function buildDirectoryTree($path, $basePath = '') {
$tree = [];
if (!is_dir($path)) return $tree;
$permissions = checkPermissions($path);
if (!$permissions['readable']) {
return $tree; // Skip unreadable directories
}
$items = @scandir($path); // Suppress errors for permission issues
if ($items === false) return $tree;
foreach ($items as $item) {
if ($item === '.' || $item === '..') continue;
$itemPath = $path . DIRECTORY_SEPARATOR . $item;
$relativePath = $basePath ? $basePath . '/' . $item : $item;
if (is_dir($itemPath)) {
$itemPermissions = checkPermissions($itemPath);
$tree[] = [
'name' => $item,
'path' => str_replace('\\', '/', $relativePath),
'type' => 'folder',
'permissions' => $itemPermissions,
'children' => $itemPermissions['readable'] ? buildDirectoryTree($itemPath, $relativePath) : []
];
} else {
// Add files to the tree
$tree[] = [
'name' => $item,
'path' => str_replace('\\', '/', $relativePath),
'type' => 'file',
'size' => filesize($itemPath),
'icon' => getFileIcon($item)
];
}
}
return $tree;
}
// CSRF Token generation
function generateCSRFToken() {
if (!isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf_token'];
}
// CSRF Token validation
function validateCSRFToken($token) {
return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}
// Authentication check
function isAuthenticated() {
return isset($_SESSION['authenticated']) &&
$_SESSION['authenticated'] === true &&
isset($_SESSION['last_activity']) &&
(time() - $_SESSION['last_activity']) < FM_SESSION_TIMEOUT;
}
// Update last activity
function updateLastActivity() {
$_SESSION['last_activity'] = time();
}
// Enhanced path sanitization for cross-platform security
function sanitizePath($path) {
// Remove directory traversal attempts
$path = str_replace(['../', '..\\', '../', '..\\'], '', $path);
// Remove dangerous characters
$path = str_replace(['<', '>', '|', ':', '*', '?', '"'], '', $path);
// Handle null bytes (security)
$path = str_replace(chr(0), '', $path);
// Normalize directory separators
$path = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $path);
// Remove leading/trailing separators
$path = trim($path, DIRECTORY_SEPARATOR);
// Additional Linux-specific checks
if (IS_LINUX) {
// Remove leading dots (hidden files protection)
$parts = explode(DIRECTORY_SEPARATOR, $path);
$parts = array_filter($parts, function($part) {
return !empty($part) && $part !== '.' && $part !== '..';
});
$path = implode(DIRECTORY_SEPARATOR, $parts);
}
return $path;
}
// Enhanced real path validation with cross-platform support
function getRealPath($path) {
$basePath = realpath(FM_ROOT_PATH);
if ($basePath === false) {
error_log("Invalid FM_ROOT_PATH: " . FM_ROOT_PATH);
return false;
}
// Normalize the base path
$basePath = normalizePath($basePath);
if (empty($path)) {
return $basePath;
}
$sanitizedPath = sanitizePath($path);
$fullPath = $basePath . DIRECTORY_SEPARATOR . $sanitizedPath;
// Resolve the real path
$realPath = realpath($fullPath);
// If realpath fails, check if parent directory exists (for new files)
if ($realPath === false) {
$parentDir = dirname($fullPath);
$realParent = realpath($parentDir);
if ($realParent !== false && strpos($realParent, $basePath) === 0) {
// Parent is valid, return the constructed path for new files
return $fullPath;
}
// Default to base path if all else fails
return $basePath;
}
// Normalize and security check
$realPath = normalizePath($realPath);
// Ensure the real path is within the base path (security check)
if (strpos($realPath, $basePath) !== 0) {
error_log("Path traversal attempt detected: " . $path);
return $basePath;
}
return $realPath;
}
// Format file size
function formatBytes($size, $precision = 2) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
for ($i = 0; $size > 1024 && $i < count($units) - 1; $i++) {
$size /= 1024;
}
return round($size, $precision) . ' ' . $units[$i];
}
// Get file icon based on extension
function getFileIcon($filename) {
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$icons = [
'php' => 'π',
'html' => 'π',
'css' => 'π¨',
'js' => 'β‘',
'json' => 'π',
'xml' => 'π',
'txt' => 'π',
'md' => 'π',
'pdf' => 'π',
'doc' => 'π',
'docx' => 'π',
'xls' => 'π',
'xlsx' => 'π',
'ppt' => 'π',
'pptx' => 'π',
'zip' => 'π¦',
'rar' => 'π¦',
'jpg' => 'πΌοΈ',
'jpeg' => 'πΌοΈ',
'png' => 'πΌοΈ',
'gif' => 'πΌοΈ',
'svg' => 'πΌοΈ',
'mp3' => 'π΅',
'mp4' => 'π¬',
'avi' => 'π¬',
'exe' => 'βοΈ',
'dll' => 'βοΈ',
];
return isset($icons[$ext]) ? $icons[$ext] : 'π';
}
// Check if file is editable
function isEditableFile($filename) {
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
$editableExts = ['php', 'html', 'css', 'js', 'json', 'xml', 'txt', 'md', 'py', 'java', 'c', 'cpp', 'h', 'sql', 'ini', 'conf', 'log'];
return in_array($ext, $editableExts) || empty($ext);
}
// Handle file operations
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isAuthenticated()) {
updateLastActivity();
$action = $_POST['action'] ?? '';
$csrfToken = $_POST['csrf_token'] ?? '';
if (!validateCSRFToken($csrfToken)) {
die('CSRF token validation failed');
}
switch ($action) {
case 'upload':
if (isset($_FILES['file'])) {
$currentDir = getRealPath($_POST['current_dir'] ?? '');
$uploadPath = $currentDir . DIRECTORY_SEPARATOR . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadPath)) {
$message = 'File uploaded successfully';
} else {
$error = 'Failed to upload file';
}
}
break;
case 'delete':
$filePath = getRealPath($_POST['path'] ?? '');
if (is_file($filePath)) {
unlink($filePath) ? $message = 'File deleted' : $error = 'Failed to delete file';
} elseif (is_dir($filePath)) {
rmdir($filePath) ? $message = 'Folder deleted' : $error = 'Failed to delete folder';
}
break;
case 'rename':
$oldPath = getRealPath($_POST['old_path'] ?? '');
$newName = basename(sanitizePath($_POST['new_name'] ?? ''));
$newPath = dirname($oldPath) . DIRECTORY_SEPARATOR . $newName;
rename($oldPath, $newPath) ? $message = 'Item renamed' : $error = 'Failed to rename';
break;
case 'create_folder':
$currentDir = getRealPath($_POST['current_dir'] ?? '');
$folderName = sanitizePath($_POST['folder_name'] ?? '');
$folderPath = $currentDir . DIRECTORY_SEPARATOR . $folderName;
mkdir($folderPath) ? $message = 'Folder created' : $error = 'Failed to create folder';
break;
case 'create_file':
$currentDir = getRealPath($_POST['current_dir'] ?? '');
$fileName = sanitizePath($_POST['file_name'] ?? '');
$filePath = $currentDir . DIRECTORY_SEPARATOR . $fileName;
file_put_contents($filePath, '') !== false ? $message = 'File created' : $error = 'Failed to create file';
break;
case 'save_file':
$filePath = getRealPath($_POST['file_path'] ?? '');
$content = $_POST['content'] ?? '';
file_put_contents($filePath, $content) !== false ? $message = 'File saved' : $error = 'Failed to save file';
break;
case 'execute_sql':
$database = $_POST['database'] ?? '';
$query = $_POST['query'] ?? '';
if ($database && $query) {
$sqlResult = executeQuery($database, $query);
if (isset($sqlResult['error'])) {
$error = 'SQL Error: ' . $sqlResult['error'];
} elseif (isset($sqlResult['data'])) {
$message = 'Query executed successfully. ' . count($sqlResult['data']) . ' rows returned.';
$_SESSION['sql_result'] = $sqlResult['data'];
$_SESSION['sql_query'] = $query;
$_SESSION['sql_database'] = $database;
} else {
$message = $sqlResult['message'];
$_SESSION['sql_result'] = null;
}
}
break;
case 'get_table_structure':
$database = $_POST['database'] ?? '';
$table = $_POST['table'] ?? '';
if ($database && $table) {
$structureResult = executeQuery($database, "DESCRIBE `$table`");
if (isset($structureResult['data'])) {
$_SESSION['table_structure'] = $structureResult['data'];
$_SESSION['current_table'] = $table;
$message = "Table structure for '$table' loaded.";
}
}
break;
}
header('Location: ' . $_SERVER['PHP_SELF'] . '?dir=' . urlencode($_POST['current_dir'] ?? '') . '&tab=' . ($_POST['tab'] ?? 'files'));
exit;
}
// Handle download
if (isset($_GET['download']) && isAuthenticated()) {
updateLastActivity();
$filePath = getRealPath($_GET['download']);
if (is_file($filePath)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filePath) . '"');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
exit;
}
}
// Handle login
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isAuthenticated()) {
$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';
if ($username === FM_USERNAME && $password === FM_PASSWORD) {
$_SESSION['authenticated'] = true;
$_SESSION['last_activity'] = time();
header('Location: ' . $_SERVER['PHP_SELF']);
exit;
} else {
$loginError = 'Invalid credentials';
}
}
// Handle logout
if (isset($_GET['logout'])) {
session_destroy();
header('Location: ' . $_SERVER['PHP_SELF']);
exit;
}
// Check authentication
if (!isAuthenticated()) {
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Manager - Login</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 min-h-screen flex items-center justify-center">
<div class="bg-white p-8 rounded-lg shadow-md w-96">
<h1 class="text-2xl font-bold text-center mb-6">π File Manager Login</h1>
<?php if (isset($loginError)): ?>
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
<?= htmlspecialchars($loginError) ?>
</div>
<?php endif; ?>
<form method="POST">
<div class="mb-4">
<label class="block text-gray-700 text-sm font-bold mb-2">Username</label>
<input type="text" name="username" required class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:border-blue-500">
</div>
<div class="mb-6">
<label class="block text-gray-700 text-sm font-bold mb-2">Password</label>
<input type="password" name="password" required class="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:border-blue-500">
</div>
<button type="submit" class="w-full bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600">
Login
</button>
</form>
<div class="mt-4 text-xs text-gray-500 text-center">
Default credentials: admin / filemanager123
</div>
</div>
</body>
</html>
<?php
exit;
}
updateLastActivity();
// Get current directory and tab
$currentDir = $_GET['dir'] ?? '';
$currentTab = $_GET['tab'] ?? 'files';
$currentPath = getRealPath($currentDir);
$relativePath = str_replace(realpath(FM_ROOT_PATH), '', $currentPath);
$relativePath = trim($relativePath, DIRECTORY_SEPARATOR);
// Get directory tree
$directoryTree = buildDirectoryTree(realpath(FM_ROOT_PATH));
// Get databases for sidebar
$databases = getDatabases();
// Handle file editing
$editFile = null;
$editContent = '';
if (isset($_GET['edit']) && isAuthenticated()) {
$editFile = getRealPath($_GET['edit']);
if (is_file($editFile) && isEditableFile($editFile)) {
$editContent = file_get_contents($editFile);
} else {
$editFile = null;
}
}
// Get directory contents
$items = [];
if (is_dir($currentPath)) {
$files = scandir($currentPath);
foreach ($files as $file) {
if ($file === '.' || $file === '..') continue;
$filePath = $currentPath . DIRECTORY_SEPARATOR . $file;
$relativePath = $currentDir ? $currentDir . '/' . $file : $file;
$permissions = checkPermissions($filePath);
$items[] = [
'name' => $file,
'path' => str_replace('\\', '/', $relativePath),
'is_dir' => is_dir($filePath),
'size' => is_file($filePath) ? filesize($filePath) : 0,
'modified' => filemtime($filePath),
'icon' => is_dir($filePath) ? 'π' : getFileIcon($file),
'editable' => is_file($filePath) && isEditableFile($file),
'permissions' => $permissions,
'owner' => $permissions['owner'] ?? 'unknown',
'group' => $permissions['group'] ?? 'unknown',
'octal' => $permissions['octal'] ?? '---'
];
}
// Sort: directories first, then files
usort($items, function($a, $b) {
if ($a['is_dir'] && !$b['is_dir']) return -1;
if (!$a['is_dir'] && $b['is_dir']) return 1;
return strcasecmp($a['name'], $b['name']);
});
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SecureFileHub - Cross-Platform File Manager</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.34.1/min/vs/loader.min.js"></script>
<style>
.monaco-editor {
height: 500px;
}
.tree-item {
cursor: pointer;
user-select: none;
}
.tree-item:hover {
background-color: #f3f4f6;
}
.tree-children {
display: none;
margin-left: 20px;
transition: all 0.3s ease;
}
.tree-children.expanded {
display: block;
}
.sidebar {
height: calc(100vh - 70px);
overflow-y: auto;
}
.main-content {
height: calc(100vh - 70px);
overflow-y: auto;
}
/* Modal Styles */
.modal {
display: none;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: hidden;
background-color: rgba(0, 0, 0, 0.7);
animation: fadeIn 0.3s;
}
.modal.show {
display: flex;
align-items: center;
justify-content: center;
}
.modal-content {
background-color: #fff;
border-radius: 8px;
width: 95%;
height: 90%;
max-width: 1400px;
display: flex;
flex-direction: column;
box-shadow: 0 10px 40px rgba(0,0,0,0.3);
animation: slideIn 0.3s;
}
.modal-header {
padding: 20px 24px;
border-bottom: 1px solid #e5e7eb;
display: flex;
justify-content: space-between;
align-items: center;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border-radius: 8px 8px 0 0;
}
.modal-body {
flex: 1;
overflow: hidden;
padding: 0;
display: flex;
flex-direction: column;
}
.modal-body form {
height: 100%;
display: flex;
flex-direction: column;
}
.modal-footer {
padding: 16px 24px;
border-top: 1px solid #e5e7eb;
display: flex;
justify-content: space-between;
align-items: center;
background-color: #f9fafb;
border-radius: 0 0 8px 8px;
}
#modalEditor {
width: 100%;
height: 100%;
flex: 1;
min-height: 0;
}
.close-btn {
font-size: 28px;
font-weight: bold;
color: white;
cursor: pointer;
line-height: 20px;
transition: transform 0.2s;
}
.close-btn:hover {
transform: scale(1.2);
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes slideIn {
from {
transform: translateY(-50px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
/* Collapsible Tree Icons */
.tree-toggle {
display: inline-block;
width: 16px;
transition: transform 0.3s;
}
.tree-toggle.collapsed {
transform: rotate(0deg);
}
.tree-toggle.expanded {
transform: rotate(90deg);
}
</style>
</head>
<body class="bg-gray-50 min-h-screen">
<!-- Enhanced Professional Header -->
<header class="bg-gradient-to-r from-blue-600 to-indigo-700 text-white shadow-xl">
<div class="container mx-auto px-4 py-3">
<div class="flex justify-between items-center">
<!-- Left: Logo and Title -->
<div class="flex items-center space-x-4">
<div class="bg-white bg-opacity-20 p-2 rounded-lg">
<svg class="w-8 h-8" fill="currentColor" viewBox="0 0 20 20">
<path d="M2 6a2 2 0 012-2h5l2 2h5a2 2 0 012 2v6a2 2 0 01-2 2H4a2 2 0 01-2-2V6z" />
</svg>
</div>
<div>
<h1 class="text-2xl font-bold tracking-tight">SecureFileHub</h1>
<p class="text-xs opacity-90">v2.0 β’ Cross-Platform File Manager</p>
</div>
</div>
<!-- Center: Breadcrumb Navigation -->
<div class="flex-1 mx-8">
<div class="bg-white bg-opacity-10 rounded-lg px-4 py-2 backdrop-blur-sm">
<div class="flex items-center text-sm">
<span class="opacity-75">π Current Path:</span>
<span class="ml-2 font-medium truncate" title="<?= htmlspecialchars($currentDir) ?>">
<?= htmlspecialchars(substr($currentDir, 0, 60) . (strlen($currentDir) > 60 ? '...' : '')) ?>
</span>
</div>
</div>
</div>
<!-- Right: System Info and User -->
<div class="flex items-center space-x-6">
<div class="text-right hidden md:block">
<div class="text-xs opacity-75">System</div>
<div class="text-sm font-semibold">
<?= IS_WINDOWS ? 'πͺ Windows' : 'π§ Linux' ?> β’ PHP <?= PHP_VERSION ?>
</div>
</div>
<div class="h-10 w-px bg-white opacity-20"></div>
<div class="flex items-center space-x-3">
<div class="text-right">
<div class="text-xs opacity-75">Logged in as</div>
<div class="text-sm font-semibold"><?= FM_USERNAME ?></div>
</div>
<a href="?logout" class="bg-red-500 bg-opacity-90 px-4 py-2 rounded-lg text-sm hover:bg-opacity-100 transition-all duration-200 font-medium shadow-lg">
πͺ Logout
</a>
</div>
</div>
</div>
</div>
</header>
<div class="flex">
<!-- Left Sidebar -->
<div class="w-80 bg-white shadow-lg sidebar border-r">
<!-- Tabs -->
<div class="flex border-b">
<button onclick="switchSidebarTab('files')" id="filesTab" class="flex-1 py-2 px-4 text-sm font-medium border-b-2 <?= $currentTab === 'files' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700' ?>">
π Files
</button>
<button onclick="switchSidebarTab('database')" id="databaseTab" class="flex-1 py-2 px-4 text-sm font-medium border-b-2 <?= $currentTab === 'database' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700' ?>">
ποΈ Database
</button>
</div>
<!-- Files Tree -->
<div id="filesContent" class="p-4 <?= $currentTab !== 'files' ? 'hidden' : '' ?>">
<div class="flex justify-between items-center mb-3">
<h3 class="text-sm font-semibold text-gray-700">Directory Structure</h3>
<div class="flex space-x-1">
<button onclick="expandAllFolders()" class="text-xs bg-blue-100 text-blue-600 px-2 py-1 rounded hover:bg-blue-200" title="Expand All Folders">
β
</button>
<button onclick="collapseAllFolders()" class="text-xs bg-gray-100 text-gray-600 px-2 py-1 rounded hover:bg-gray-200" title="Collapse All Folders">
β
</button>
</div>
</div>
<div class="tree">
<?php renderTree($directoryTree); ?>
</div>
</div>
<!-- Database Tree -->
<div id="databaseContent" class="p-4 <?= $currentTab !== 'database' ? 'hidden' : '' ?>">
<h3 class="text-sm font-semibold text-gray-700 mb-3">MySQL Databases</h3>
<?php if (empty($databases)): ?>
<p class="text-gray-500 text-sm">β Database connection failed</p>
<?php else: ?>
<div class="space-y-2">
<?php foreach ($databases as $db): ?>
<div class="tree-item p-2 rounded text-sm" onclick="toggleDatabase('<?= htmlspecialchars($db) ?>')">
<span class="toggle-icon">βΆ</span>
<span class="ml-1">ποΈ <?= htmlspecialchars($db) ?></span>
<div class="tree-children" id="db-<?= htmlspecialchars($db) ?>">
<!-- Tables will be loaded here -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php endif; ?>
</div>
</div>
<!-- Main Content Area -->
<div class="flex-1 main-content">
<div class="p-6">
<!-- Messages -->
<?php if (isset($message)): ?>
<div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded mb-4">
<?= htmlspecialchars($message) ?>
</div>
<?php endif; ?>
<?php if (isset($error)): ?>
<div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
<?= htmlspecialchars($error) ?>
</div>
<?php endif; ?>
<!-- Main Content Tabs -->
<div class="bg-white rounded-lg shadow mb-6">
<div class="border-b border-gray-200">
<nav class="-mb-px flex space-x-8">
<a href="?tab=files&dir=<?= urlencode($currentDir) ?>" class="py-2 px-1 border-b-2 font-medium text-sm <?= $currentTab === 'files' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' ?>">
π File Manager
</a>
<a href="?tab=database&dir=<?= urlencode($currentDir) ?>" class="py-2 px-1 border-b-2 font-medium text-sm <?= $currentTab === 'database' ? 'border-blue-500 text-blue-600' : 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' ?>">
ποΈ Database Manager
</a>
</nav>
</div>
<div class="p-6">
<?php if ($currentTab === 'files'): ?>
<!-- File Manager Content -->
<div class="flex items-center justify-between mb-4">
<div class="flex items-center space-x-2">
<span class="text-gray-600">π</span>
<span class="font-medium">Current Path:</span>
<span class="text-blue-600"><?= $currentDir ?: '/' ?></span>
</div>
<?php if ($currentDir): ?>
<a href="?tab=files&dir=<?= urlencode(dirname($currentDir)) ?>" class="bg-gray-500 text-white px-3 py-1 rounded text-sm hover:bg-gray-600">
β¬οΈ Up
</a>
<?php endif; ?>
</div>
<!-- File Operations Cards -->
<div class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
<!-- Upload File -->
<form method="POST" enctype="multipart/form-data" class="bg-gradient-to-br from-blue-50 to-blue-100 p-4 rounded-lg border border-blue-200 shadow-sm hover:shadow-md transition-shadow">
<input type="hidden" name="action" value="upload">
<input type="hidden" name="current_dir" value="<?= htmlspecialchars($currentDir) ?>">
<input type="hidden" name="tab" value="files">
<input type="hidden" name="csrf_token" value="<?= generateCSRFToken() ?>">
<label class="block text-sm font-semibold mb-2 text-blue-700">π€ Upload File</label>
<input type="file" name="file" required class="w-full text-xs mb-2 file:mr-2 file:py-1 file:px-3 file:rounded file:border-0 file:text-sm file:bg-blue-500 file:text-white hover:file:bg-blue-600 file:cursor-pointer">
<button type="submit" class="w-full bg-blue-600 text-white py-2 px-3 rounded-lg text-sm font-medium hover:bg-blue-700 transition-colors shadow-sm">Upload</button>
</form>
<!-- Create Folder -->
<form method="POST" class="bg-gradient-to-br from-green-50 to-green-100 p-4 rounded-lg border border-green-200 shadow-sm hover:shadow-md transition-shadow">
<input type="hidden" name="action" value="create_folder">
<input type="hidden" name="current_dir" value="<?= htmlspecialchars($currentDir) ?>">
<input type="hidden" name="tab" value="files">
<input type="hidden" name="csrf_token" value="<?= generateCSRFToken() ?>">
<label class="block text-sm font-semibold mb-2 text-green-700">π Create Folder</label>
<input type="text" name="folder_name" required placeholder="Folder name" class="w-full px-3 py-2 border border-green-300 rounded-lg text-sm mb-2 focus:ring-2 focus:ring-green-500 focus:border-transparent">
<button type="submit" class="w-full bg-green-600 text-white py-2 px-3 rounded-lg text-sm font-medium hover:bg-green-700 transition-colors shadow-sm">Create</button>
</form>
<!-- Create File -->
<form method="POST" class="bg-gradient-to-br from-yellow-50 to-yellow-100 p-4 rounded-lg border border-yellow-200 shadow-sm hover:shadow-md transition-shadow">
<input type="hidden" name="action" value="create_file">
<input type="hidden" name="current_dir" value="<?= htmlspecialchars($currentDir) ?>">
<input type="hidden" name="tab" value="files">
<input type="hidden" name="csrf_token" value="<?= generateCSRFToken() ?>">
<label class="block text-sm font-semibold mb-2 text-yellow-700">π Create File</label>
<input type="text" name="file_name" required placeholder="file.txt" class="w-full px-3 py-2 border border-yellow-300 rounded-lg text-sm mb-2 focus:ring-2 focus:ring-yellow-500 focus:border-transparent">
<button type="submit" class="w-full bg-yellow-600 text-white py-2 px-3 rounded-lg text-sm font-medium hover:bg-yellow-700 transition-colors shadow-sm">Create</button>
</form>
<!-- Actions -->
<div class="bg-gradient-to-br from-gray-50 to-gray-100 p-4 rounded-lg border border-gray-200 shadow-sm hover:shadow-md transition-shadow">
<label class="block text-sm font-semibold mb-2 text-gray-700">π Quick Actions</label>
<a href="?tab=files" class="block w-full bg-gray-600 text-white py-2 px-3 rounded-lg text-sm text-center font-medium hover:bg-gray-700 transition-colors shadow-sm mb-2">Refresh View</a>
<?php if ($editFile): ?>
<button onclick="toggleEditor()" class="w-full bg-purple-600 text-white py-2 px-3 rounded-lg text-sm font-medium hover:bg-purple-700 transition-colors shadow-sm">Hide Editor</button>
<?php else: ?>
<button onclick="showEditorInfo()" class="w-full bg-purple-500 text-white py-1 px-2 rounded text-sm hover:bg-purple-600">Editor Info</button>
<?php endif; ?>
</div>
</div>
<!-- File List -->
<div class="bg-white rounded-lg shadow overflow-hidden">
<table class="w-full">
<thead class="bg-gray-50">
<tr>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Name</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Size</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Modified</th>
<?php if (IS_LINUX): ?>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Permissions</th>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Owner</th>
<?php endif; ?>
<th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-200">
<?php foreach ($items as $item): ?>
<tr class="hover:bg-gray-50">
<td class="px-4 py-3">
<div class="flex items-center">
<span class="mr-2"><?= $item['icon'] ?></span>
<?php if ($item['is_dir']): ?>
<a href="?tab=files&dir=<?= urlencode($item['path']) ?>" class="text-blue-600 hover:underline">
<?= htmlspecialchars($item['name']) ?>
</a>
<?php else: ?>
<span><?= htmlspecialchars($item['name']) ?></span>
<?php endif; ?>
</div>
</td>
<td class="px-4 py-3 text-sm text-gray-600">
<?= $item['is_dir'] ? '-' : formatBytes($item['size']) ?>
</td>
<td class="px-4 py-3 text-sm text-gray-600">
<?= date('Y-m-d H:i:s', $item['modified']) ?>
</td>
<?php if (IS_LINUX): ?>
<td class="px-4 py-3 text-sm text-gray-600">
<span class="font-mono text-xs"><?= $item['octal'] ?></span>
<div class="text-xs text-gray-500">
<?= $item['permissions']['readable'] ? 'r' : '-' ?>
<?= $item['permissions']['writable'] ? 'w' : '-' ?>
<?= $item['permissions']['executable'] ? 'x' : '-' ?>
</div>
</td>
<td class="px-4 py-3 text-sm text-gray-600">
<div class="text-xs">