-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.php
1433 lines (1212 loc) · 404 KB
/
index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
session_start();
# $configFileName = rtrim($dir, '/') . '/config.php';
$repo_url = "https://github.com/poikilos/directory-listing";
$configFileName = dirname(__FILE__)."/config.php";
if (!file_exists($configFileName)) {
$error = "Could not find $configFileName. It should be in the same directory as " . basename(__FILE__) . " from $repo_url";
echo $error;
//throw new Exception($error);
}
include($configFileName);
$verbosity = 0;
function echo0($msg) {
# See <https://stackoverflow.com/a/6079566>.
file_put_contents('php://stderr', print_r("$msg\n", TRUE));
return true;
}
function echo1($msg) {
global $verbosity;
if ($verbosity < 1) return false;
return echo0($msg);
}
function echo2($msg) {
global $verbosity;
if ($verbosity < 2) return false;
return echo0($msg);
}
//region patch versions of PHP before 8:
if (!function_exists("str_starts_with")) {
function str_starts_with($haystack, $needle) {
$length = strlen($needle);
return $length > 0 ? substr($haystack, 0, $length) === $needle : true;
}
}
if (!function_exists("str_ends_with")) {
function str_ends_with($haystack, $needle) {
$length = strlen($needle);
return $length > 0 ? substr($haystack, -$length) === $needle : true;
}
}
//endregion patch versions of PHP before 8:
function conf_to_dict($path) {
$handle = fopen($path, "r");
$section = null;
$results = array();
$ao = "=";
echo1("Reading $path:");
if ($handle) {
while (($raw_line = fgets($handle)) !== false) {
$line = trim($raw_line);
if (strlen($line) == 0) {
continue;
}
if (str_starts_with($line, "[")) {
if (str_ends_with($line, "]")) {
$section = substr($line, 1, -1);
if (!in_array($section, $results)) {
$results[$section] = array();
}
echo2("section='$section'"); //for debug only
}
else {
throw new Exception("The line in $path starts with '[' but doesn't end with ']'.");
}
continue;
}
$aoi = strpos($line, $ao); // assignment operator index
if ($aoi === false) {
continue;
}
$key = trim(substr($line, 0, $aoi));
$value = trim(substr($line, $aoi+1));
if ($section === null) {
$results[$key] = $value;
echo2(" [$key]=$value");
}
else {
$results[$section][$key] = $value;
echo2(" [$section][$key]=$value");
}
}
fclose($handle);
}
return $results;
}
class DirectoryListing
{
/*
====================================================================================================
Evoluted Directory Listing Script - Version 4
Poikilos' fork (from https://github.com/poikilos/directory-listing; See readme for changes.).
(originally from www.evoluted.net / info@evoluted.net)
====================================================================================================
SYSTEM REQUIREMENTS
====================================================================================================
This script requires a PHP version 5.3 or above (5.6 is the recommended minimum) along with the GD
library if you wish to use the thumbnail/image preview functionality. For (optional) unzip
functionality, you'll need the ZipArchive php extension.
HOW TO USE
====================================================================================================
1) Unzip the provided files.
2) Upload the index.php file to the directory you wish to use the script on
3) Browse to the directory to see the script in action
4) Optionally change any of the settings below
CONFIGURATION
====================================================================================================
You may edit any of the variables in this section to alter how the directory listing script will
function. Please read the notes above each variable for details on what they change.
These values can be placed in a config.php file with the same format as config.example.php.
*/
// The top level directory where this script is located, or alternatively one of it's sub-directories
public $startDirectory = '.';
// An optional title to show in the address bar and at the top of your page (set to null to leave blank)
public $pageTitle = 'Evoluted Directory Listing Script';
// The URL of this script. Optionally set if your server is unable to detect the paths of files
public $includeUrl = false;
// If you've enabled the includeUrl parameter above, enter the full url to the directory the index.php file
// is located in here, followed by a forward slash.
public $directoryUrl = 'https://example.com/main-directory-name-here/';
// Set to true to list all sub-directories and allow them to be browsed
public $showSubDirectories = true;
// Set to true to open all file links in a new browser tab
public $openLinksInNewTab = true;
// Set to true to show thumbnail previews of any images
public $showThumbnails = true;
// Set to true to show an audio player for audio files
public $showAudio = true;
// Set to true to allow new directories to be created.
public $enableDirectoryCreation = true;
// Set to true to allow file uploads (NOTE: you should set a password if you enable this!)
public $enableUploads = true;
// Enable multi-file uploads (NOTE: This makes use of javascript libraries hosted by Google so an internet connection is required.)
public $enableMultiFileUploads = true;
// Set to true to overwrite files on the server if they have the same name as a file being uploaded
public $overwriteOnUpload = false;
// Set to true to enable file deletion options
public $enableFileDeletion = true;
// Set to true to enable directory deletion options (only available when the directory is empty)
public $enableDirectoryDeletion = true;
// List of all mime types that can be uploaded. Full list of mime types: http://www.iana.org/assignments/media-types/media-types.xhtml
public $allowedUploadMimeTypes = array(
'image/jpeg',
'image/gif',
'image/png',
'image/bmp',
'audio/mpeg',
'audio/mp3',
'audio/mp4',
'audio/x-aac',
'audio/x-aiff',
'audio/x-ms-wma',
'audio/midi',
'audio/ogg',
'video/ogg',
'video/webm',
'video/quicktime',
'video/x-msvideo',
'video/x-flv',
'video/h261',
'video/h263',
'video/h264',
'video/jpeg',
'text/plain',
'text/html',
'text/css',
'text/csv',
'text/calendar',
'application/pdf',
'application/x-pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document', // MS Word (modern)
'application/msword',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // MS Excel (modern)
'application/zip',
'application/x-tar',
'text/blnk',
'application/x-desktop',
);
// Set to true to unzip any zip files that are uploaded (note - will overwrite files of the same name!)
public $enableUnzipping = true;
// If you've enabled unzipping, you can optionally delete the original zip file after its uploaded by setting this to true.
public $deleteZipAfterUploading = false;
// The Evoluted Directory Listing Script uses Bootstrap. By setting this value to true, a nicer theme will be loaded remotely.
// Setting this to false will make the directory listing script use the default bootstrap style, loaded locally.
public $enableTheme = true;
// Set to true to require a password be entered before being able to use the script
public $passwordProtect = false;
// The password to require to use this script (only used if $passwordProtect is set to true)
public $password = 'password';
// Optional. Allow restricted access only to whitelisted IP addresses
public $enableIpWhitelist = false;
// List of IP's to allow access to the script (only used if $enableIpWhitelist is true)
public $ipWhitelist = array(
'127.0.0.1',
);
// File extensions to block from showing in the directory listing
public $ignoredFileExtensions = array(
'php',
'ini',
);
// File names to block from showing in the directory listing
public $ignoredFileNames = array(
'.htaccess',
'.DS_Store',
'Thumbs.db',
);
// Directories to block from showing in the directory listing
public $ignoredDirectories = array(
);
// Files that begin with a dot are usually hidden files. Set this to false if you wish to show these hiden files.
public $ignoreDotFiles = true;
// Works the same way as $ignoreDotFiles but with directories.
public $ignoreDotDirectories = true;
/*
====================================================================================================
You shouldn't need to edit anything below this line unless you wish to add functionality to the
script. You should only edit this area if you know what you are doing!
====================================================================================================
*/
private $__previewMimeTypes = array(
'image/gif',
'image/jpeg',
'image/png',
'image/bmp',
);
private $__audioMimeTypes = array(
'audio/basic',
'auido/L24',
'audio/mid',
'audio/mpeg',
'audio/mp4',
'audio/x-aiff',
'audio/x-mpegurl',
'audio/vnd.rn-realaudio',
'audio/ogg',
'audio/vorbis',
'audio/vnd.wav',
);
private $__audioExtensions = array(
'mp3',
'ogg',
);
private $__currentDirectory = null;
private $__fileList = array();
private $__directoryList = array();
private $__debug = true;
public $sortBy = 'name';
public $sortableFields = array(
'name',
'size',
'modified',
);
private $__sortOrder = 'asc';
public function __construct()
{
global $CONFIG;
define('DS', '/');
if (isset($CONFIG)) {
/*
foreach ($this as $key => $value) {
if (array_key_exists($key, $CONFIG)) {
$this->{$key} = $CONFIG[$key];
}
}
*/
foreach ($CONFIG as $key => $value) {
$this->{$key} = $CONFIG[$key];
}
}
}
public function run()
{
if ($this->enableIpWhitelist) {
$this->__ipWhitelistCheck();
}
$this->__currentDirectory = $this->startDirectory;
// Sorting
if (isset($_GET['order']) && in_array($_GET['order'], $this->sortableFields)) {
$this->sortBy = $_GET['order'];
}
if (isset($_GET['sort']) && ($_GET['sort'] == 'asc' || $_GET['sort'] == 'desc')) {
$this->__sortOrder = $_GET['sort'];
}
if (isset($_GET['dir'])) {
if (isset($_GET['delete']) && $this->enableDirectoryDeletion) {
$this->deleteDirectory();
}
$this->__currentDirectory = $_GET['dir'];
return $this->__display();
} elseif (isset($_GET['preview'])) {
$this->__generatePreview($_GET['preview']);
} else {
return $this->__display();
}
}
public function login()
{
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);
if ($password === $this->password) {
$_SESSION['evdir_loggedin'] = true;
unset($_SESSION['evdir_loginfail']);
} else {
$_SESSION['evdir_loginfail'] = true;
unset($_SESSION['evdir_loggedin']);
}
}
public function upload()
{
$files = $this->__formatUploadArray($_FILES['upload']);
if ($this->enableUploads) {
if ($this->enableMultiFileUploads) {
foreach ($files as $file) {
$status = $this->__processUpload($file);
}
} else {
$file = $files[0];
$status = $this->__processUpload($file);
}
return $status;
}
return false;
}
private function __formatUploadArray($files)
{
$fileAry = array();
$fileCount = count($files['name']);
$fileKeys = array_keys($files);
for ($i = 0; $i < $fileCount; ++$i) {
foreach ($fileKeys as $key) {
$fileAry[$i][$key] = $files[$key][$i];
}
}
return $fileAry;
}
private function __processUpload($file)
{
if (isset($_GET['dir'])) {
$this->__currentDirectory = $_GET['dir'];
}
if (!$this->__currentDirectory) {
$filePath = realpath($this->startDirectory);
} else {
$this->__currentDirectory = str_replace('..', '', $this->__currentDirectory);
$this->__currentDirectory = ltrim($this->__currentDirectory, '/');
$filePath = realpath($this->__currentDirectory);
}
$filePath = $filePath.DS.$file['name'];
if (!empty($file)) {
if (!$this->overwriteOnUpload) {
if (file_exists($filePath)) {
return 2;
}
}
if (!in_array(mime_content_type($file['tmp_name']), $this->allowedUploadMimeTypes)) {
return 3;
}
move_uploaded_file($file['tmp_name'], $filePath);
if (mime_content_type($filePath) == 'application/zip' && $this->enableUnzipping && class_exists('ZipArchive')) {
$zip = new ZipArchive();
$result = $zip->open($filePath);
$zip->extractTo(realpath($this->__currentDirectory));
$zip->close();
if ($this->deleteZipAfterUploading) {
// Delete the zip file
unlink($filePath);
}
}
return true;
}
}
public function deleteFile()
{
if (isset($_GET['deleteFile'])) {
$file = $_GET['deleteFile'];
// Clean file path
$file = str_replace('..', '', $file);
$file = ltrim($file, '/');
// Work out full file path
$filePath = __DIR__.$this->__currentDirectory.'/'.$file;
if (file_exists($filePath) && is_file($filePath)) {
return unlink($filePath);
}
return false;
}
}
public function deleteDirectory()
{
if (isset($_GET['dir'])) {
$dir = $_GET['dir'];
// Clean dir path
$dir = str_replace('..', '', $dir);
$dir = ltrim($dir, '/');
// Work out full directory path
$dirPath = __DIR__.'/'.$dir;
if (file_exists($dirPath) && is_dir($dirPath)) {
$iterator = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
$files = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($files as $file) {
if ($file->isDir()) {
rmdir($file->getRealPath());
} else {
unlink($file->getRealPath());
}
}
return rmdir($dir);
}
}
return false;
}
public function createDirectory()
{
if ($this->enableDirectoryCreation) {
$directoryName = $_POST['directory'];
// Convert spaces
$directoryName = str_replace(' ', '_', $directoryName);
// Clean up formatting
$directoryName = preg_replace('/[^\w-_]/', '', $directoryName);
if (isset($_GET['dir'])) {
$this->__currentDirectory = $_GET['dir'];
}
if (!$this->__currentDirectory) {
$filePath = realpath($this->startDirectory);
} else {
$this->__currentDirectory = str_replace('..', '', $this->__currentDirectory);
$filePath = realpath($this->__currentDirectory);
}
$filePath = $filePath.DS.strtolower($directoryName);
if (file_exists($filePath)) {
return false;
}
return mkdir($filePath, 0755);
}
return false;
}
public function sortUrl($sort)
{
// Get current URL parts
$urlParts = parse_url($_SERVER['REQUEST_URI']);
$url = '';
if (isset($urlParts['scheme'])) {
$url = $urlParts['scheme'].'://';
}
if (isset($urlParts['host'])) {
$url .= $urlParts['host'];
}
if (isset($urlParts['path'])) {
$url .= $urlParts['path'];
}
// Extract query string
if (isset($urlParts['query'])) {
$queryString = $urlParts['query'];
parse_str($queryString, $queryParts);
// work out if we're already sorting by the current heading
if (isset($queryParts['order']) && $queryParts['order'] == $sort) {
// Yes we are, just switch the sort option!
if (isset($queryParts['sort'])) {
if ($queryParts['sort'] == 'asc') {
$queryParts['sort'] = 'desc';
} else {
$queryParts['sort'] = 'asc';
}
}
} else {
$queryParts['order'] = $sort;
$queryParts['sort'] = 'asc';
}
// Now convert back to a string
$queryString = http_build_query($queryParts);
$url .= '?'.$queryString;
} else {
$order = 'asc';
if ($sort == $this->sortBy) {
$order = 'desc';
}
$queryString = 'order='.$sort.'&sort='.$order;
$url .= '?'.$queryString;
}
return $url;
}
public function sortClass($sort)
{
$class = $sort.'_';
if ($this->sortBy == $sort) {
if ($this->__sortOrder == 'desc') {
$class .= 'desc sort_desc';
} else {
$class .= 'asc sort_asc';
}
} else {
$class = '';
}
return $class;
}
private function __ipWhitelistCheck()
{
// Get the users ip
$userIp = $_SERVER['REMOTE_ADDR'];
if (!in_array($userIp, $this->ipWhitelist)) {
header('HTTP/1.0 403 Forbidden');
die('Your IP address ('.$userIp.') is not authorized to access this file.');
}
}
private function __display()
{
if ($this->__currentDirectory != '.' && !$this->__endsWith($this->__currentDirectory, DS)) {
$this->__currentDirectory = $this->__currentDirectory.DS;
}
return $this->__loadDirectory($this->__currentDirectory);
}
private function __loadDirectory($path)
{
$files = $this->__scanDir($path);
if (!empty($files)) {
// Strip excludes files, directories and filetypes
$files = $this->__cleanFileList($files);
foreach ($files as $file) {
$filePath = realpath($this->__currentDirectory.DS.$file);
if ($this->__isDirectory($filePath)) {
if (!$this->includeUrl) {
$urlParts = parse_url($_SERVER['REQUEST_URI']);
$dirUrl = '';
if (isset($urlParts['scheme'])) {
$dirUrl = $urlParts['scheme'].'://';
}
if (isset($urlParts['host'])) {
$dirUrl .= $urlParts['host'];
}
if (isset($urlParts['path'])) {
$dirUrl .= $urlParts['path'];
}
} else {
$dirUrl = $this->directoryUrl;
}
if ($this->__currentDirectory != '' && $this->__currentDirectory != '.') {
$dirUrl .= '?dir='.rawurlencode($this->__currentDirectory).rawurlencode($file);
} else {
$dirUrl .= '?dir='.rawurlencode($file);
}
$this->__directoryList[$file] = array(
'name' => rawurldecode($file),
'path' => $filePath,
'type' => 'dir',
'url' => $dirUrl,
);
} else {
// echo "$file";
$this->__fileList[$file] = $this->__getFileType($filePath, $this->__currentDirectory.DS.$file);
}
}
}
if (!$this->showSubDirectories) {
$this->__directoryList = null;
}
$data = array(
'currentPath' => $this->__currentDirectory,
'directoryTree' => $this->__getDirectoryTree(),
'files' => $this->__setSorting($this->__fileList),
'directories' => $this->__directoryList,
'requirePassword' => $this->passwordProtect,
'enableUploads' => $this->enableUploads,
);
return $data;
}
private function __setSorting($data)
{
$sortOrder = '';
$sortBy = '';
// Sort the files
if ($this->sortBy == 'name') {
function compareByName($a, $b)
{
return strnatcasecmp($a['name'], $b['name']);
}
usort($data, 'compareByName');
$this->soryBy = 'name';
} elseif ($this->sortBy == 'size') {
function compareBySize($a, $b)
{
return strnatcasecmp($a['size_bytes'], $b['size_bytes']);
}
usort($data, 'compareBySize');
$this->soryBy = 'size';
} elseif ($this->sortBy == 'modified') {
function compareByModified($a, $b)
{
return strnatcasecmp($a['modified'], $b['modified']);
}
usort($data, 'compareByModified');
$this->soryBy = 'modified';
}
if ($this->__sortOrder == 'desc') {
$data = array_reverse($data);
}
return $data;
}
private function __scanDir($dir)
{
// Prevent browsing up the directory path.
if (strstr($dir, '../')) {
return false;
}
if ($dir == '/') {
$dir = $this->startDirectory;
$this->__currentDirectory = $dir;
}
$strippedDir = str_replace('/', '', $dir);
$dir = ltrim($dir, '/');
// Prevent listing blacklisted directories
if (in_array($strippedDir, $this->ignoredDirectories)) {
return false;
}
if (!file_exists($dir) || !is_dir($dir)) {
return false;
}
return scandir($dir);
}
private function __cleanFileList($files)
{
$this->ignoredDirectories[] = '.';
$this->ignoredDirectories[] = '..';
foreach ($files as $key => $file) {
// Remove unwanted directories
if ($this->__isDirectory(realpath($file)) && in_array($file, $this->ignoredDirectories)) {
unset($files[$key]);
}
// Remove dot directories (if enables)
if ($this->ignoreDotDirectories && substr($file, 0, 1) === '.') {
unset($files[$key]);
}
// Remove unwanted files
if (!$this->__isDirectory(realpath($file)) && in_array($file, $this->ignoredFileNames)) {
unset($files[$key]);
}
// Remove unwanted file extensions
if (!$this->__isDirectory(realpath($file))) {
$info = pathinfo(mb_convert_encoding($file, 'UTF-8', 'UTF-8'));
if (isset($info['extension'])) {
$extension = $info['extension'];
if (in_array($extension, $this->ignoredFileExtensions)) {
unset($files[$key]);
}
}
// If dot files want ignoring, do that next
if ($this->ignoreDotFiles) {
if (substr($file, 0, 1) == '.') {
unset($files[$key]);
}
}
}
}
return $files;
}
private function __isDirectory($file)
{
if ($file == $this->__currentDirectory.DS.'.' || $file == $this->__currentDirectory.DS.'..') {
return true;
}
$file = mb_convert_encoding($file, 'UTF-8', 'UTF-8');
if (filetype($file) == 'dir') {
return true;
}
return false;
}
/**
* __getFileType.
*
* Returns the formatted array of file data used for thre directory listing.
*
* @param string $filePath Full path to the file
*
* @return array Array of data for the file
*/
private function __getFileType($filePath, $relativePath = null)
{
$fi = new finfo(FILEINFO_MIME_TYPE);
if (!file_exists($filePath)) {
return false;
}
$type = $fi->file($filePath);
if (str_ends_with($filePath, ".blnk")) {
$type = "text/blnk";
}
elseif (str_ends_with($filePath, ".desktop")) {
$type = "application/x-desktop";
}
$filePathInfo = pathinfo($filePath);
$extension = (isset($filePathInfo['extension']) ? $filePathInfo['extension'] : null);
$fileSize = filesize($filePath);
$fileModified = filemtime($filePath);
$filePreview = false;
// Check if the file type supports previews
if ($this->__supportsPreviews($type) && $this->showThumbnails) {
$filePreview = true;
}
$fileAudio = false;
if ($this->__supportsAudio($type, $extension) && $this->showAudio) {
$fileAudio = true;
}
// moved from return array so they can be overridden:
$url = $this->__getUrl($filePathInfo['basename']);
$basename = $filePathInfo['basename'];
echo2("\nextension=$extension");
$blnkUrl = null;
if ($extension == "blnk") {
$blnk = conf_to_dict($filePath);
$basename = $blnk['Name'];
if ($blnk['Type'] == "Link") {
$url = $blnk['URL'];
// $blnkParsedUrl = parse_url($url);
// TODO: download the site icon:
// $blnkRoot = $blnkParsedUrl['scheme'] . '://' . $blnkParsedUrl['host'];
// $iconUrl = "$blnkRoot/favicon.ico";
}
}
elseif ($extension == "desktop") {
$blnk = conf_to_dict($filePath);
echo2("$filePath:");
foreach ($blnk as $key => $value) {
echo2(" $key: $value");
}
$basename = $blnk['Desktop Entry']['Name'];
if ($blnk['Desktop Entry']['Type'] == "Link") {
$url = $blnk['Desktop Entry']['URL'];
$blnkParsedUrl = parse_url($url);
$blnkRoot = $blnkParsedUrl['scheme'] . '://' . $blnkParsedUrl['host'] . '/';
}
}
return array(
'name' => $basename,
'extension' => $extension,
'dir' => $filePathInfo['dirname'],
'path' => $filePath,
'relativePath' => $relativePath,
'size' => $this->__formatSize($fileSize),
'size_bytes' => $fileSize,
'modified' => $fileModified,
'type' => 'file',
'mime' => $type,
'url' => $url,
'preview' => $filePreview,
'audio' => $fileAudio,
'target' => ($this->openLinksInNewTab ? '_blank' : '_parent'),
);
}
private function __supportsPreviews($type)
{
if (in_array($type, $this->__previewMimeTypes)) {
return true;
}
return false;
}
private function __supportsAudio($type, $extension)
{
if (in_array($type, $this->__audioMimeTypes) || in_array($extension, $this->__audioExtensions)) {
return true;
}
return false;
}
/**
* __getUrl.
*
* Returns the url to the file.
*
* @param string $file filename
*
* @return string url of the file
*/
private function __getUrl($file)
{
if (!$this->includeUrl) {
$dirUrl = $_SERVER['REQUEST_URI'];
$urlParts = parse_url($_SERVER['REQUEST_URI']);
$dirUrl = '';
if (isset($urlParts['scheme'])) {
$dirUrl = $urlParts['scheme'].'://';
}
if (isset($urlParts['host'])) {
$dirUrl .= $urlParts['host'];
}
if (isset($urlParts['path'])) {
$dirUrl .= $urlParts['path'];
}
} else {
$dirUrl = $this->directoryUrl;
}
if ($this->__currentDirectory != '.') {
$dirUrl = $dirUrl.$this->__currentDirectory;
}
return $dirUrl.rawurlencode($file);
}
private function __getDirectoryTree()
{
$dirString = $this->__currentDirectory;
$directoryTree = array();
$directoryTree['./'] = 'Index';
if (substr_count($dirString, '/') >= 0) {
$items = explode('/', $dirString);
$items = array_filter($items);
$path = '';
foreach ($items as $item) {
if ($item == '.' || $item == '..') {
continue;
}
$path .= rawurlencode($item).'/';
$directoryTree[$path] = $item;
}
}
$directoryTree = array_filter($directoryTree);
return $directoryTree;
}
private function __endsWith($haystack, $needle)
{
return $needle === '' || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
}
private function __generatePreview($filePath)