-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.php
More file actions
3922 lines (3468 loc) · 132 KB
/
index.php
File metadata and controls
3922 lines (3468 loc) · 132 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
/**
* LocalhostIndex - Security Hardened Version
* A beautiful localhost homepage for local development environments.
*
* SECURITY: This tool is for LOCAL DEVELOPMENT ONLY.
* Set 'enable_security' => true if deploying on shared/public servers.
*/
// Configuration constants
define( 'CSRF_TOKEN_LENGTH', 32 ); // Length of CSRF token in bytes
define( 'MYSQL_TIMEOUT', 2 ); // MySQL connection timeout in seconds
define( 'RECENT_ITEMS_LIMIT', 10 ); // Number of recent items to display (extended)
define( 'RECENT_ITEMS_PREVIEW', 2 ); // Number of recent items in preview (folded)
define( 'CACHE_TTL', 60 ); // Cache time-to-live in seconds
define( 'MAX_LOGIN_ATTEMPTS', 5 ); // Maximum failed login attempts before lockout
define( 'LOCKOUT_DURATION', 300 ); // Lockout duration in seconds (5 minutes)
define( 'DIR_MAX_DEPTH', 2 ); // Maximum recursion depth for directory size calculation
$options = [
/**
* Set the theme
* Available themes: bluey, sunny, forest, retro, matrix, nebula, sundown, monochrome, dark, light
*/
'theme' => 'bluey',
/**
* Exclude files or folders
* use wildcard pattern. eg: ['.git*', '*.exe', '*.sh', '*.php*', '*.png']
*/
'exclude' => [ '.DS_Store', '.localized', '*.php*', '*.png' ],
/**
* Add extra tools
* [label] => '[link of the tool]
* eg: 'phpMyAdmin' => 'http://localhost/phpMyAdmin'
* Note: phpinfo link will automatically include CSRF token if enabled
*/
'extras' => [
'phpinfo()' => '?phpinfo=1',
'PhpMyAdmin()' => 'phpMyAdmin'
],
/**
* Set one or more favicon file names to look for (relative to this directory).
* Provide a string or an array; the first existing file will be used.
*/
'favicon' => [ 'favicon.ico', 'favicon.png', 'favicon.svg' ],
/**
* MySQL detection options
* - 'bin' => array|string of explicit mysql/mysqld binary paths/commands
* - 'connection' => [
* 'host' => '127.0.0.1',
* 'user' => 'root',
* 'password' => 'secret',
* 'database' => null,
* 'port' => 3306,
* 'socket' => null,
* 'timeout' => 2
* ]
*/
'mysql' => [],
/**
* Display Settings
* Customize how files and folders are displayed
*/
'display' => [
// Show file sizes in directory listing
'show_file_sizes' => true,
// Default sort order: 'name', 'date', 'size'
'default_sort' => 'name',
// Enable caching (improves performance with many files)
'enable_cache' => true,
],
/**
* Security Settings
* Enable these for shared or public-facing servers
*/
'security' => [
// Enable authentication (recommended for non-localhost)
'enable_authentication' => false,
// Simple password protection (use strong password if enabled)
'password' => '', // Leave empty to disable, or set a password hash via password_hash('your_password', PASSWORD_DEFAULT)
// Disable phpinfo for security
'disable_phpinfo' => false,
// Enable CSRF protection
'enable_csrf' => true,
// Validate all paths against traversal
'strict_path_validation' => true,
]
];
// Security: Session management
session_start();
// Security: Generate CSRF token
if( !isset( $_SESSION['csrf_token'] ) ){
$_SESSION['csrf_token'] = bin2hex( random_bytes( CSRF_TOKEN_LENGTH ) );
}
// Security: HTTP Headers
header( 'X-Content-Type-Options: nosniff' );
header( 'X-Frame-Options: SAMEORIGIN' );
header( 'X-XSS-Protection: 1; mode=block' );
header( 'Referrer-Policy: strict-origin-when-cross-origin' );
// Security: Simple authentication check with rate limiting
if( !empty( $options['security']['enable_authentication'] ) && !empty( $options['security']['password'] ) ){
if( !isset( $_SESSION['authenticated'] ) ){
// Rate limiting using constants
$maxAttempts = MAX_LOGIN_ATTEMPTS;
$lockoutTime = LOCKOUT_DURATION;
// Initialize rate limiting session vars
if( !isset( $_SESSION['login_attempts'] ) ){
$_SESSION['login_attempts'] = 0;
$_SESSION['lockout_until'] = 0;
}
// Check if currently locked out
if( $_SESSION['lockout_until'] > time() ){
$remaining = $_SESSION['lockout_until'] - time();
$login_error = "Too many attempts. Try again in {$remaining} seconds.";
}
// Handle login form (only if not locked out)
elseif( isset( $_POST['password'] ) && isset( $_POST['csrf_token'] ) ){
if( hash_equals( $_SESSION['csrf_token'], $_POST['csrf_token'] ) ){
if( password_verify( $_POST['password'], $options['security']['password'] ) ){
// Success: reset attempts and authenticate
$_SESSION['login_attempts'] = 0;
$_SESSION['lockout_until'] = 0;
session_regenerate_id( true );
$_SESSION['authenticated'] = true;
header( 'Location: ' . $_SERVER['PHP_SELF'] );
exit;
} else {
// Failed: increment attempts
$_SESSION['login_attempts']++;
if( $_SESSION['login_attempts'] >= $maxAttempts ){
$_SESSION['lockout_until'] = time() + $lockoutTime;
$login_error = "Too many attempts. Try again in {$lockoutTime} seconds.";
} else {
$remaining = $maxAttempts - $_SESSION['login_attempts'];
$login_error = "Invalid password. {$remaining} attempts remaining.";
}
}
}
}
// Show login form
if( !isset( $_SESSION['authenticated'] ) ){
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>LocalhostIndex - Login</title>
<style>
body { font-family: monospace; display: flex; align-items: center; justify-content: center; min-height: 100vh; background: #102252; color: #f4f6ff; margin: 0; }
.login-box { background: rgba(255,255,255,0.05); padding: 40px; border-radius: 8px; max-width: 350px; }
h1 { margin-top: 0; font-size: 18px; letter-spacing: 2px; }
input { width: 100%; padding: 12px; margin: 10px 0; border: none; border-radius: 4px; font-family: monospace; box-sizing: border-box; }
button { width: 100%; padding: 12px; background: #d9e009; border: none; border-radius: 4px; font-weight: bold; cursor: pointer; font-family: monospace; }
button:hover { opacity: 0.9; }
.error { color: #ff6b6b; margin: 10px 0; font-size: 13px; }
</style>
</head>
<body>
<div class="login-box">
<h1>LOCALHOSTINDEX</h1>
<?php if( isset( $login_error ) ): ?>
<div class="error"><?= htmlspecialchars( $login_error, ENT_QUOTES, 'UTF-8' ); ?></div>
<?php endif; ?>
<form method="post">
<input type="password" name="password" placeholder="Password" required autofocus>
<input type="hidden" name="csrf_token" value="<?= htmlspecialchars( $_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8' ); ?>">
<button type="submit">Login</button>
</form>
</div>
</body>
</html>
<?php
exit;
}
}
}
// Security: Validate and sanitize paths
function validatePath( string $filename, bool $strict = true ): bool {
// Reject dangerous characters (null bytes, control chars, shell metacharacters)
if( preg_match( '/[<>:"|?*\x00-\x1f]/', $filename ) ){
return false;
}
// Prevent path traversal
if( strpos( $filename, '..' ) !== false ){
return false;
}
// Additional strict validation with proper symlink handling
if( $strict ){
$basePath = realpath( __DIR__ );
if( $basePath === false ){
return false;
}
$fullPath = __DIR__ . DIRECTORY_SEPARATOR . $filename;
$realPath = realpath( $fullPath );
// Path must exist
if( $realPath === false ){
return false;
}
// Strict prefix check: must be within base directory
// Use DIRECTORY_SEPARATOR to prevent partial matches (e.g., /var/www vs /var/www2)
if( $realPath !== $basePath && strpos( $realPath, $basePath . DIRECTORY_SEPARATOR ) !== 0 ){
return false;
}
}
return true;
}
// display phpinfo with CSRF protection (POST preferred for security)
if( isset( $_GET['phpinfo'] ) && $_GET['phpinfo'] === '1' ){
// Check if phpinfo is disabled
if( !empty( $options['security']['disable_phpinfo'] ) ){
http_response_code( 403 );
die( 'phpinfo() has been disabled for security.' );
}
// CSRF protection - accept POST token (preferred) or GET token (legacy)
if( !empty( $options['security']['enable_csrf'] ) ){
$token = $_POST['csrf_token'] ?? $_GET['token'] ?? '';
if( empty( $token ) || !hash_equals( $_SESSION['csrf_token'], $token ) ){
http_response_code( 403 );
die( 'Invalid security token.' );
}
}
phpinfo();
exit;
}
/**
* Get Apache version string (extracted for DRY principle)
*/
function getApacheVersion(): ?string {
if( !function_exists( 'apache_get_version' ) ){
return null;
}
$versionString = apache_get_version();
if( $versionString === false ){
return null;
}
$parts = explode( '/', $versionString );
if( !isset( $parts[1] ) ){
return null;
}
return explode( ' ', $parts[1] )[0];
}
// Health check endpoint for monitoring
if( isset( $_GET['health'] ) ){
header( 'Content-Type: application/json' );
echo json_encode([
'status' => 'ok',
'timestamp' => time(),
'php_version' => PHP_VERSION,
'server' => getApacheVersion() ?? 'unknown'
]);
exit;
}
/**
* Detect runtime version by sourcing user's shell profile
* This ensures version managers (pyenv, nvm, rbenv, etc.) are loaded
*/
function detectRuntimeVersion( string $command, string $versionFlag = '--version', string $pattern = '/(\d+\.\d+[\.\d]*)/' ): ?string {
// Find user's shell profile to source version managers
$homeDir = getenv( 'HOME' );
$profiles = [ '.zshrc', '.bashrc', '.bash_profile', '.profile' ];
$sourceCmd = '';
if( $homeDir ){
foreach( $profiles as $profile ){
$profilePath = $homeDir . '/' . $profile;
if( file_exists( $profilePath ) ){
$sourceCmd = "source $profilePath 2>/dev/null && ";
break;
}
}
}
// Execute command with sourced environment (uses safeShellExec for graceful degradation)
$fullCommand = escapeshellcmd( $command ) . ' ' . $versionFlag;
$cmd = "bash -c '" . $sourceCmd . $fullCommand . "' 2>/dev/null";
$output = safeShellExec( $cmd );
if( $output === null || trim( $output ) === '' ){
return null;
}
$output = trim( $output );
if( preg_match( $pattern, $output, $matches ) ){
return $matches[1];
}
return null;
}
/**
* Detect open localhost ports with running services
* Returns array of ports with process info
*/
function detectOpenPorts(): array {
$ports = [];
// Common development port ranges
$portRanges = [
[ 3000, 3999 ], // Node.js apps (Express, React, etc.)
[ 4000, 4999 ], // Various dev servers
[ 5000, 5999 ], // Flask, Vite, etc.
[ 8000, 8999 ], // Django, PHP dev servers, etc.
[ 9000, 9999 ], // Various services
];
if( PHP_OS_FAMILY === 'Darwin' ){
// macOS: Use lsof for reliable port detection
$output = safeShellExec( "lsof -iTCP -sTCP:LISTEN -n -P 2>/dev/null | grep -E ':(3[0-9]{3}|4[0-9]{3}|5[0-9]{3}|8[0-9]{3}|9[0-9]{3})'" );
if( $output ){
$lines = explode( "\n", trim( $output ) );
foreach( $lines as $line ){
if( empty( $line ) ) continue;
// Parse lsof output: COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
if( preg_match( '/^(\S+)\s+(\d+)\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+\s+\S+:(\d+)/', $line, $matches ) ){
$process = strtolower( $matches[1] );
$pid = (int)$matches[2];
$port = (int)$matches[3];
// Filter to common development port ranges only
$inRange = ( $port >= 3000 && $port <= 3999 ) ||
( $port >= 4000 && $port <= 4999 ) ||
( $port >= 5000 && $port <= 5999 ) ||
( $port >= 8000 && $port <= 8999 ) ||
( $port >= 9000 && $port <= 9999 );
if( !$inRange ) continue;
// Skip known macOS system services (not dev servers)
$systemProcesses = [ 'controlce', 'airplayd', 'rapportd', 'sharingd' ];
if( in_array( $process, $systemProcesses, true ) ) continue;
// Skip php-fpm on port 9000 (background FastCGI service, not a dev server)
if( $process === 'php-fpm' && $port === 9000 ) continue;
// Skip if already found (can have multiple entries per port)
$exists = false;
foreach( $ports as $p ){
if( $p['port'] === $port ){
$exists = true;
break;
}
}
if( $exists ) continue;
// Map process names to friendly names
$processName = match( true ){
str_contains( $process, 'node' ) => 'Node.js',
str_contains( $process, 'python' ) => 'Python',
str_contains( $process, 'ruby' ) => 'Ruby',
str_contains( $process, 'php' ) => 'PHP',
str_contains( $process, 'go' ) => 'Go',
str_contains( $process, 'java' ) => 'Java',
str_contains( $process, 'nginx' ) => 'nginx',
str_contains( $process, 'httpd' ) || str_contains( $process, 'apache' ) => 'Apache',
str_contains( $process, 'docker' ) => 'Docker',
str_contains( $process, 'com.docke' ) => 'Docker',
default => ucfirst( $process )
};
// Get command and working directory for more detail
$detail = '';
$cmdOutput = safeShellExec( "ps -p {$pid} -o args= 2>/dev/null" );
if( $cmdOutput ){
$cmd = trim( $cmdOutput );
// Extract the tool/script being run
if( preg_match( '/\/(flask|django|uvicorn|gunicorn|manage\.py)\b/', $cmd, $m ) ){
// Python frameworks
$detail = $m[1];
if( preg_match( '/(run|runserver|serve)/', $cmd ) ) $detail .= ' run';
} elseif( preg_match( '/\/(eleventy|vite|webpack|next|nuxt|remix|astro|parcel|esbuild|rollup|tsx?)\b/', $cmd, $m ) ){
// Node.js tools
$detail = $m[1];
} elseif( preg_match( '/([^\s\/]+\.(js|ts|py|rb|php|go))(?:\s|$)/', $cmd, $m ) ){
// Script files
$detail = $m[1];
} elseif( preg_match( '/node_modules\/\.bin\/([^\s\/]+)/', $cmd, $m ) ){
// npm binaries
$detail = $m[1];
} elseif( preg_match( '/\s-m\s+(\S+)/', $cmd, $m ) ){
// Python -m module
$detail = $m[1];
}
}
// Get project folder from cwd
$cwdOutput = safeShellExec( "lsof -p {$pid} -a -d cwd 2>/dev/null | tail -1 | awk '{print \$NF}'" );
if( $cwdOutput ){
$cwd = trim( $cwdOutput );
$folder = basename( $cwd );
if( $folder && $folder !== '/' && $folder !== 'Sites' ){
$detail = $detail ? "{$detail} · {$folder}" : $folder;
}
}
$ports[] = [
'port' => $port,
'process' => $processName,
'pid' => $pid,
'detail' => $detail
];
}
}
}
} elseif( PHP_OS_FAMILY === 'Linux' ){
// Linux: Try ss first (modern), fallback to netstat
$output = safeShellExec( "ss -tlnp 2>/dev/null | grep -E ':(3[0-9]{3}|4[0-9]{3}|5[0-9]{3}|8[0-9]{3}|9[0-9]{3})'" );
if( $output === null ){
$output = safeShellExec( "netstat -tlnp 2>/dev/null | grep -E ':(3[0-9]{3}|4[0-9]{3}|5[0-9]{3}|8[0-9]{3}|9[0-9]{3})'" );
}
if( $output ){
$lines = explode( "\n", trim( $output ) );
foreach( $lines as $line ){
if( empty( $line ) ) continue;
// Parse ss/netstat output for port and process
if( preg_match( '/:(\d+)\s/', $line, $portMatch ) ){
$port = (int)$portMatch[1];
// Filter to common development port ranges only
$inRange = ( $port >= 3000 && $port <= 3999 ) ||
( $port >= 4000 && $port <= 4999 ) ||
( $port >= 5000 && $port <= 5999 ) ||
( $port >= 8000 && $port <= 8999 ) ||
( $port >= 9000 && $port <= 9999 );
if( !$inRange ) continue;
// Skip if already found
$exists = false;
foreach( $ports as $p ){
if( $p['port'] === $port ){
$exists = true;
break;
}
}
if( $exists ) continue;
// Try to extract process name
$processName = 'Unknown';
$pid = null;
if( preg_match( '/users:\(\("([^"]+)",pid=(\d+)/', $line, $procMatch ) ){
$processName = ucfirst( $procMatch[1] );
$pid = (int)$procMatch[2];
} elseif( preg_match( '/(\d+)\/(\S+)/', $line, $procMatch ) ){
$pid = (int)$procMatch[1];
$processName = ucfirst( $procMatch[2] );
}
// Get command and working directory for more detail
$detail = '';
if( $pid ){
$cmdOutput = safeShellExec( "ps -p {$pid} -o args= 2>/dev/null" );
if( $cmdOutput ){
$cmd = trim( $cmdOutput );
if( preg_match( '/\/(flask|django|uvicorn|gunicorn|manage\.py)\b/', $cmd, $m ) ){
$detail = $m[1];
if( preg_match( '/(run|runserver|serve)/', $cmd ) ) $detail .= ' run';
} elseif( preg_match( '/\/(eleventy|vite|webpack|next|nuxt|remix|astro|parcel|esbuild|rollup|tsx?)\b/', $cmd, $m ) ){
$detail = $m[1];
} elseif( preg_match( '/([^\s\/]+\.(js|ts|py|rb|php|go))(?:\s|$)/', $cmd, $m ) ){
$detail = $m[1];
} elseif( preg_match( '/node_modules\/\.bin\/([^\s\/]+)/', $cmd, $m ) ){
$detail = $m[1];
} elseif( preg_match( '/\s-m\s+(\S+)/', $cmd, $m ) ){
$detail = $m[1];
}
}
$cwdOutput = safeShellExec( "lsof -p {$pid} -a -d cwd 2>/dev/null | tail -1 | awk '{print \$NF}'" );
if( $cwdOutput ){
$cwd = trim( $cwdOutput );
$folder = basename( $cwd );
if( $folder && $folder !== '/' && $folder !== 'Sites' ){
$detail = $detail ? "{$detail} · {$folder}" : $folder;
}
}
}
$ports[] = [
'port' => $port,
'process' => $processName,
'pid' => $pid,
'detail' => $detail
];
}
}
}
}
// Sort by port number
usort( $ports, fn( $a, $b ) => $a['port'] <=> $b['port'] );
return $ports;
}
/**
* Auto-detect installed runtimes and their versions (true parallel for speed)
*/
function detectRuntimes(): array {
$runtimes = [];
// Web Server (instant - PHP function)
$apacheVersion = getApacheVersion();
if( $apacheVersion !== null ){
$runtimes['Apache'] = $apacheVersion;
}
// PHP (instant - always available)
$runtimes['PHP'] = explode( '-', phpversion() )[0];
// MySQL (instant - direct path)
$mysqlPaths = [ '/usr/local/mysql/bin/mysql', '/opt/homebrew/bin/mysql' ];
foreach( $mysqlPaths as $mysqlBin ){
$output = @shell_exec( escapeshellarg( $mysqlBin ) . ' --version 2>/dev/null' );
if( $output && preg_match( '/Ver\\s+([0-9.]+)/i', $output, $m ) ){
$runtimes['MySQL'] = $m[1];
break;
}
}
// Define all tools to detect: [label, command, flag, pattern]
$tools = [
[ 'Python', 'python3', '--version', '/Python (\d+\.\d+\.\d+)/' ],
[ 'pip', 'pip3', '--version', '/pip (\d+\.\d+[\.\d]*)/' ],
[ 'Node.js', 'node', '--version', '/v?(\d+\.\d+\.\d+)/' ],
[ 'npm', 'npm', '--version', '/(\d+\.\d+[\.\d]*)/' ],
[ 'Ruby', 'ruby', '--version', '/ruby (\d+\.\d+\.\d+)/' ],
[ 'Go', 'go', 'version', '/go(\d+\.\d+[\.\d]*)/' ],
[ 'Composer', 'composer', '--version', '/(\d+\.\d+\.\d+)/' ],
[ 'Git', 'git', '--version', '/git version (\d+\.\d+[\.\d]*)/' ],
[ 'Docker', 'docker', '--version', '/Docker version (\d+\.\d+\.\d+)/' ],
[ 'Homebrew', 'brew', '--version', '/Homebrew (\d+\.\d+\.\d+)/' ],
[ 'PostgreSQL', 'psql', '--version', '/(\d+\.\d+[\.\d]*)/' ],
[ 'Redis', 'redis-server', '--version', '/v=(\d+\.\d+\.\d+)/' ],
[ 'Java', 'java', '--version', '/(\d+\.\d+[\.\d]*)/' ],
[ 'Rust', 'rustc', '--version', '/rustc (\d+\.\d+\.\d+)/' ],
[ 'MongoDB', 'mongod', '--version', '/v(\d+\.\d+\.\d+)/' ],
[ 'SQLite', 'sqlite3', '--version', '/(\d+\.\d+\.\d+)/' ],
[ 'TypeScript', 'tsc', '--version', '/(\d+\.\d+\.\d+)/' ],
[ 'Swift', 'swift', '--version', '/Swift version (\d+\.\d+[\.\d]*)/' ],
[ '.NET', 'dotnet', '--version', '/(\d+\.\d+[\.\d]*)/' ],
[ 'GitHub CLI', 'gh', '--version', '/gh version (\d+\.\d+\.\d+)/' ],
[ 'Claude', 'claude', '--version', '/(\d+\.\d+\.\d+)/' ],
[ 'Codex', 'codex', '--version', '/(\d+\.\d+\.\d+)/' ],
[ 'Gemini', 'gemini', '--version', '/(\d+\.\d+\.\d+)/' ],
];
// Create temp directory for parallel output
$tmpDir = sys_get_temp_dir() . '/lhi_' . getmypid();
@mkdir( $tmpDir, 0755, true );
// Source shell profile for version managers (pyenv, nvm, etc.)
$homeDir = getenv( 'HOME' );
$sourceCmd = '';
if( $homeDir ){
foreach( [ '.zshrc', '.bashrc', '.bash_profile', '.profile' ] as $profile ){
$profilePath = "$homeDir/$profile";
if( file_exists( $profilePath ) ){
$sourceCmd = "source $profilePath 2>/dev/null; ";
break;
}
}
}
// Build parallel shell script: run all commands in background, wait, collect
$bgCmds = [];
foreach( $tools as $i => $tool ){
[ $label, $cmd, $flag ] = $tool;
$outFile = "$tmpDir/t$i";
$bgCmds[] = "($cmd $flag 2>&1 | head -1 > $outFile) &";
}
$bgCmds[] = 'wait';
// Execute all in parallel with sourced environment
$script = implode( "\n", $bgCmds );
@shell_exec( "bash -c '{$sourceCmd}{$script}' 2>/dev/null" );
// Collect results
foreach( $tools as $i => $tool ){
[ $label, $cmd, $flag, $pattern ] = $tool;
$outFile = "$tmpDir/t$i";
if( file_exists( $outFile ) ){
$output = trim( @file_get_contents( $outFile ) );
@unlink( $outFile );
if( $output && preg_match( $pattern, $output, $m ) ){
$runtimes[$label] = $m[1];
}
}
}
// Cleanup
@rmdir( $tmpDir );
return $runtimes;
}
// AJAX endpoint for extended runtime detection
if( isset( $_GET['action'] ) && $_GET['action'] === 'detect_runtimes' ){
// Verify CSRF token if enabled
if( !empty( $options['security']['enable_csrf'] ) ){
if( !isset( $_GET['token'] ) || !hash_equals( $_SESSION['csrf_token'], $_GET['token'] ) ){
http_response_code( 403 );
die( json_encode( [ 'error' => 'Invalid token' ] ) );
}
}
header( 'Content-Type: application/json' );
echo json_encode( detectRuntimes() );
exit;
}
// AJAX endpoint for server stats (deferred loading for faster page load)
if( isset( $_GET['action'] ) && $_GET['action'] === 'server_stats' ){
// Verify CSRF token if enabled
if( !empty( $options['security']['enable_csrf'] ) ){
if( !isset( $_GET['token'] ) || !hash_equals( $_SESSION['csrf_token'], $_GET['token'] ) ){
http_response_code( 403 );
die( json_encode( [ 'error' => 'Invalid token' ] ) );
}
}
$stats = [];
// Apache connections (only if Apache is running)
if( function_exists( 'apache_get_modules' ) ){
$apacheStatus = safeShellExec( "netstat -an 2>/dev/null | grep -cE ':(80|443).*ESTABLISHED'" );
if( $apacheStatus !== null ){
$stats['Apache connections'] = trim( $apacheStatus );
}
}
// Active ports - optimized command
$activePorts = safeShellExec( "netstat -an 2>/dev/null | grep -c LISTEN" );
if( $activePorts !== null ){
$stats['Active ports'] = trim( $activePorts );
}
// Running processes - SINGLE ps call instead of 3
if( PHP_OS_FAMILY === 'Darwin' || PHP_OS_FAMILY === 'Linux' ){
$psOutput = safeShellExec( "ps aux 2>/dev/null" );
if( $psOutput !== null ){
$procCounts = [];
$apacheCount = preg_match_all( '/httpd|apache2/i', $psOutput );
$mysqlCount = preg_match_all( '/mysqld/i', $psOutput );
$nodeCount = preg_match_all( '/\bnode\b/i', $psOutput );
if( $apacheCount > 0 ) $procCounts[] = "Apache: {$apacheCount}";
if( $mysqlCount > 0 ) $procCounts[] = "MySQL: {$mysqlCount}";
if( $nodeCount > 0 ) $procCounts[] = "Node: {$nodeCount}";
if( !empty( $procCounts ) ){
$stats['Running processes'] = implode( ', ', $procCounts );
}
}
}
header( 'Content-Type: application/json' );
echo json_encode( $stats );
exit;
}
// AJAX endpoint for detecting open localhost ports
if( isset( $_GET['action'] ) && $_GET['action'] === 'detect_ports' ){
// Verify CSRF token if enabled
if( !empty( $options['security']['enable_csrf'] ) ){
if( !isset( $_GET['token'] ) || !hash_equals( $_SESSION['csrf_token'], $_GET['token'] ) ){
http_response_code( 403 );
die( json_encode( [ 'error' => 'Invalid token' ] ) );
}
}
header( 'Content-Type: application/json' );
echo json_encode( [ 'ports' => detectOpenPorts() ] );
exit;
}
// AJAX endpoint for killing a process by PID
if( isset( $_POST['action'] ) && $_POST['action'] === 'kill_process' ){
header( 'Content-Type: application/json' );
// Verify CSRF token if enabled
if( !empty( $options['security']['enable_csrf'] ) ){
if( !isset( $_POST['token'] ) || !hash_equals( $_SESSION['csrf_token'], $_POST['token'] ) ){
http_response_code( 403 );
die( json_encode( [ 'success' => false, 'message' => 'Invalid token' ] ) );
}
}
$pid = isset( $_POST['pid'] ) ? (int)$_POST['pid'] : 0;
if( $pid <= 0 ){
echo json_encode( [ 'success' => false, 'message' => 'Invalid PID' ] );
exit;
}
// Kill the process (only works for processes owned by current user)
if( PHP_OS_FAMILY === 'Darwin' || PHP_OS_FAMILY === 'Linux' ){
@shell_exec( "kill {$pid} 2>/dev/null" );
// Always return success - the refresh will show if it actually worked
echo json_encode( [ 'success' => true, 'message' => "Signal sent to {$pid}" ] );
} else {
echo json_encode( [ 'success' => false, 'message' => 'Not supported on this platform' ] );
}
exit;
}
// AJAX endpoint for quick actions
if( isset( $_POST['action'] ) ){
// IMPORTANT: Set content type first, before any output
header( 'Content-Type: application/json' );
// Verify CSRF token if enabled
if( !empty( $options['security']['enable_csrf'] ) ){
if( !isset( $_POST['token'] ) || !hash_equals( $_SESSION['csrf_token'], $_POST['token'] ) ){
http_response_code( 403 );
die( json_encode( [ 'success' => false, 'message' => 'Invalid token' ] ) );
}
}
$action = $_POST['action'];
$result = [ 'success' => false, 'message' => 'Unknown action' ];
switch( $action ){
case 'clear-opcache':
if( function_exists( 'opcache_reset' ) ){
opcache_reset();
$result = [ 'success' => true, 'message' => 'OPcache cleared successfully' ];
} else {
$result = [ 'success' => false, 'message' => 'OPcache not available' ];
}
break;
case 'clear-sessions':
$sessionPath = session_save_path() ?: sys_get_temp_dir();
$realPath = realpath( $sessionPath );
if( $realPath === false || !is_dir( $realPath ) ){
$result = [ 'success' => false, 'message' => 'Invalid session path' ];
break;
}
$count = 0;
$errors = 0;
try {
$iterator = new DirectoryIterator( $realPath );
foreach( $iterator as $file ){
if( $file->isFile() && strpos( $file->getFilename(), 'sess_' ) === 0 ){
if( @unlink( $file->getPathname() ) ){
$count++;
} else {
$errors++;
}
}
}
$result = [ 'success' => true, 'message' => "Cleared {$count} session files" . ( $errors > 0 ? " ({$errors} failed)" : '' ) ];
} catch( Exception $e ){
$result = [ 'success' => false, 'message' => 'Failed to access session directory' ];
}
break;
}
echo json_encode( $result );
exit;
}
// Detect basic info only (fast - no shell sourcing, no network calls)
// MySQL detection moved to AJAX endpoint for faster page load
function detectBasicInfo(): array {
$info = [];
// Web Server (instant - PHP function)
$apacheVersion = getApacheVersion();
if( $apacheVersion !== null ){
$info['Apache'] = $apacheVersion;
}
// PHP (instant - always available)
$info['PHP'] = explode( '-', phpversion() )[0];
// MySQL/MariaDB - try direct path first (fast)
$mysqlOutput = @shell_exec( "'/usr/local/mysql/bin/mysql' --version 2>/dev/null" );
if( !$mysqlOutput ){
$mysqlOutput = @shell_exec( "'/opt/homebrew/bin/mysql' --version 2>/dev/null" );
}
if( $mysqlOutput && preg_match( '/Ver\s+([0-9.]+)/i', $mysqlOutput, $m ) ){
$info['MySQL'] = $m[1];
}
return $info;
}
// Load basic info only on page load
$info = detectBasicInfo();
// match a given filename against an array of patterns
function filenameMatch( array $patternArray, string $filename ): bool {
if( empty( $patternArray ) ){
return false;
}
foreach( $patternArray as $pattern ){
if( fnmatch( $pattern, $filename ) ){
return true;
}
}
return false;
}
/**
* Attempt to detect the MySQL server version using CLI tools or optional connection details.
*/
function detectMysqlVersion( array $mysqlOptions = [] ): string {
$mysqlOptions = is_array( $mysqlOptions ) ? $mysqlOptions : [];
$binary_candidates = [];
if( !empty( $mysqlOptions['bin'] ) ){
$binary_candidates = array_merge(
$binary_candidates,
is_array( $mysqlOptions['bin'] ) ? $mysqlOptions['bin'] : [ $mysqlOptions['bin'] ]
);
}
if( !empty( $mysqlOptions['binary'] ) ){
$binary_candidates = array_merge(
$binary_candidates,
is_array( $mysqlOptions['binary'] ) ? $mysqlOptions['binary'] : [ $mysqlOptions['binary'] ]
);
}
// Most common MySQL paths (ordered by likelihood on macOS/Linux)
$default_binaries = [
'/usr/local/mysql/bin/mysql',
'/opt/homebrew/bin/mysql',
'/usr/local/bin/mysql',
'/usr/bin/mysql',
'/opt/local/bin/mysql',
'mysql',
'/usr/local/mysql/bin/mysqld',
'/usr/sbin/mysqld',
'/usr/libexec/mysqld',
'mysqld'
];
$binary_candidates = array_values(
array_unique(
array_filter(
array_merge( $binary_candidates, $default_binaries ),
static fn( $binary ) => is_string( $binary ) && trim( $binary ) !== ''
)
)
);
// Try first 5 candidates for better detection while keeping good performance
foreach( array_slice( $binary_candidates, 0, 5 ) as $binary ){
$binary = trim( (string) $binary );
if( $binary === '' ){
continue;
}
$escaped_binary = escapeshellarg( $binary );
$output = safeShellExec( $escaped_binary . ' --version 2>/dev/null' );
if( $output === null || trim( $output ) === '' ){
continue;
}
$output = trim( $output );
if( preg_match( '/Distrib\\s+([0-9.]+)/i', $output, $matches ) ){
return $matches[1];
}
if( preg_match( '/Ver\\s+([0-9.]+)/i', $output, $matches ) ){
return $matches[1];
}
}
$connection = $mysqlOptions['connection'] ?? [];
$host = $connection['host'] ?? $connection['hostname'] ?? ini_get( 'mysqli.default_host' );
$port = $connection['port'] ?? ini_get( 'mysqli.default_port' );
$socket = $connection['socket'] ?? ini_get( 'mysqli.default_socket' );
$user = $connection['user'] ?? $connection['username'] ?? ini_get( 'mysqli.default_user' );
$password = $connection['password'] ?? $connection['pass'] ?? $connection['pw'] ?? ini_get( 'mysqli.default_pw' );
$database = $connection['database'] ?? $connection['dbname'] ?? null;
$timeout = isset( $connection['timeout'] ) ? (int) $connection['timeout'] : MYSQL_TIMEOUT;
$env_user = getenv( 'DB_USER' )
?: getenv( 'MYSQL_USER' )
?: getenv( 'JAWSDB_USERNAME' )
?: getenv( 'JAWSDB_USER' )
?: getenv( 'CLEARDB_USERNAME' );
$env_password = getenv( 'DB_PASSWORD' )
?: getenv( 'MYSQL_PASSWORD' )
?: getenv( 'JAWSDB_PASSWORD' )
?: getenv( 'CLEARDB_PASSWORD' );
$env_host = getenv( 'DB_HOST' )
?: getenv( 'MYSQL_HOST' )
?: getenv( 'JAWSDB_HOST' )
?: getenv( 'CLEARDB_HOST' );
$env_db = getenv( 'DB_NAME' )
?: getenv( 'MYSQL_DATABASE' )
?: getenv( 'MYSQL_DB' )
?: getenv( 'JAWSDB_DATABASE' )
?: getenv( 'CLEARDB_DATABASE' );
$env_port = getenv( 'DB_PORT' )
?: getenv( 'MYSQL_PORT' )
?: getenv( 'JAWSDB_PORT' )
?: getenv( 'CLEARDB_PORT' );
if( empty( $user ) && !empty( $env_user ) ){
$user = $env_user;
}
if( $password === null && $env_password !== false ){
$password = $env_password;
}
if( empty( $host ) && !empty( $env_host ) ){
$host = $env_host;
}
if( empty( $database ) && !empty( $env_db ) ){
$database = $env_db;
}
if( empty( $port ) && !empty( $env_port ) ){
$port = $env_port;
}
$database_url = getenv( 'DATABASE_URL' ) ?: getenv( 'JAWSDB_URL' ) ?: getenv( 'CLEARDB_DATABASE_URL' );
if( !empty( $database_url ) ){
$url_parts = parse_url( $database_url );
if( is_array( $url_parts ) ){
if( empty( $user ) && !empty( $url_parts['user'] ) ){
$user = $url_parts['user'];
}
if( $password === null && isset( $url_parts['pass'] ) ){
$password = $url_parts['pass'];
}
if( empty( $host ) && !empty( $url_parts['host'] ) ){
$host = $url_parts['host'];
}
if( empty( $port ) && !empty( $url_parts['port'] ) ){
$port = $url_parts['port'];
}
if( empty( $database ) && !empty( $url_parts['path'] ) ){
$database = ltrim( $url_parts['path'], '/' );
}
}
}
$host = $host !== '' ? $host : null;
$port = !empty( $port ) ? (int) $port : null;
$socket = !empty( $socket ) ? $socket : null;
$password = $password !== null ? (string) $password : '';
// Disable mysqli exceptions for detection (PHP 8.x throws by default)
$prevReporting = mysqli_report( MYSQLI_REPORT_OFF );
// Build list of connection attempts: user-provided first, then defaults
$attempts = [];
if( !empty( $user ) || $socket !== null ){
$attempts[] = [ 'host' => $host, 'user' => $user, 'pass' => $password, 'port' => $port, 'socket' => $socket ];
}
// Always try common local defaults as fallback
$attempts[] = [ 'host' => '127.0.0.1', 'user' => 'root', 'pass' => '', 'port' => 3306, 'socket' => null ];
$attempts[] = [ 'host' => 'localhost', 'user' => 'root', 'pass' => '', 'port' => 3306, 'socket' => null ];
// Try socket connection (common on macOS)
$attempts[] = [ 'host' => null, 'user' => 'root', 'pass' => '', 'port' => null, 'socket' => '/tmp/mysql.sock' ];
foreach( $attempts as $attempt ){
$mysqli = @mysqli_init();
if( $mysqli ){
if( defined( 'MYSQLI_OPT_CONNECT_TIMEOUT' ) ){
@mysqli_options( $mysqli, MYSQLI_OPT_CONNECT_TIMEOUT, $timeout );
}
// Suppress connection errors as this is detection, not critical functionality
$connected = @mysqli_real_connect(
$mysqli,
$attempt['host'],
$attempt['user'],
$attempt['pass'],
$database,
$attempt['port'],
$attempt['socket']
);
if( $connected ){