-
Notifications
You must be signed in to change notification settings - Fork 76
/
index.php
3142 lines (2471 loc) · 142 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
/* Files Gallery 0.11.0
www.files.gallery | www.files.gallery/docs/ | www.files.gallery/docs/license/
---
This PHP file is only 10% of the application, used only to connect with the file system. 90% of the codebase, including app logic, interface, design and layout is managed by the app Javascript and CSS files.
---
class Config / load config with static methods to access config options
class Login / check and manage logins
class U / static utility functions
class Path / static functions to convert and validate file paths
class Json / JSON response functions
class X3 / helper functions when running Files Gallery alongside X3 www.photo.gallery
class Tests / outputs PHP, server and config diagnostics by url ?action=tests
class FileResponse / outputs file, video preview image, resized image and proxies any file by PHP
class ResizeImage / serves a resized image
class Dirs / outputs menu json from dir structure
class Dir / loads data array for a single dir
class File / returns data array for a single file
class Iptc / extract IPTC image data from images
class Exif / extract Exif image data from images
class Filemanager / functions that handle file operations on server
class Zipper / create and extract zip files
class Request / extract parameters for all actions
class Document / creates the main Files Gallery document response
*/
// class Config / constructor and static methods to access config options
class Config {
// config defaults / https://www.files.gallery/docs/config/
// Only edit directly here if it is a temporary installation. Settings here will be lost when updating!
// Instead, add options into external config file in your storage_path _files/config/config.php (generated on first run)
private static $default = [
'root' => '',
'root_url_path' => null,
'start_path' => false,
'username' => '',
'password' => '',
'load_images' => true,
'load_files_proxy_php' => false,
'load_images_max_filesize' => 1000000,
'image_resize_enabled' => true,
'image_resize_cache' => true,
'image_resize_dimensions' => 320,
'image_resize_dimensions_retina' => 480,
'image_resize_dimensions_allowed' => '',
'image_resize_types' => 'jpeg, png, gif, webp, bmp, avif',
'image_resize_quality' => 85,
'image_resize_function' => 'imagecopyresampled',
'image_resize_sharpen' => true,
'image_resize_memory_limit' => 256,
'image_resize_max_pixels' => 60000000,
'image_resize_min_ratio' => 1.5,
'image_resize_cache_direct' => false,
'folder_preview_image' => true,
'folder_preview_default' => '_filespreview.jpg',
'menu_enabled' => true,
'menu_max_depth' => 5,
'menu_sort' => 'name_asc',
'menu_cache_validate' => true,
'menu_load_all' => false,
'menu_recursive_symlinks' => true,
'layout' => 'rows',
'cache' => true,
'cache_key' => 0,
'storage_path' => '_files',
'files_exclude' => '',
'dirs_exclude' => '',
'allow_symlinks' => true,
'get_mime_type' => false,
'license_key' => '',
'download_dir' => 'browser',
'download_dir_cache' => 'dir',
'assets' => '',
'allow_all' => false,
'allow_upload' => false,
'allow_delete' => false,
'allow_rename' => false,
'allow_new_folder' => false,
'allow_new_file' => false,
'allow_duplicate' => false,
'allow_text_edit' => false,
'allow_zip' => false,
'allow_unzip' => false,
'allow_move' => false,
'allow_copy' => false,
'allow_download' => true,
'allow_mass_download' => false,
'allow_mass_copy_links' => false,
'allow_check_updates' => false,
'allow_tests' => true,
'allow_tasks' => false,
'demo_mode' => false,
'upload_allowed_file_types' => '',
'upload_max_filesize' => 0,
'upload_exists' => 'increment',
'video_thumbs' => true,
'video_ffmpeg_path' => 'ffmpeg',
'pdf_thumbs' => true,
'imagemagick_path' => 'magick',
'use_google_docs_viewer' => false,
'lang_default' => 'en',
'lang_auto' => true,
];
// global application variables created on new Config()
public static $version = '0.11.0'; // Files Gallery version
public static $config = []; // config array merged from _filesconfig.php, config.php and default config
public static $localconfigpath = '_filesconfig.php'; // optional config file in current dir, useful when overriding shared configs
public static $localconfig = []; // config array from localconfigpath
public static $storagepath; // absolute storage path for cache, config, plugins and more, normally _files dir
public static $storageconfigpath; // absolute path to storage config, normally _files/config/config.php
public static $storageconfig = []; // config array from storage path, normally _files/config/config.php
public static $cachepath; // absolute cache path shortcut
public static $__dir__; // absolute __DIR__ path with normalized OS path
public static $__file__; // absolute __FILE__ path with normalized OS path
public static $root; // absolute root path interpolated from config root option, normally current dir
public static $document_root; // absolute server document root with normalized OS path
public static $is_logged_in; // detect if user is logged in
public static $created = []; // checks what dirs and files get created by config on ?action=tests
// config construct created static app vars and merge configs
public function __construct() {
// get absolute __DIR__ and __FILE__ paths with normalized OS paths
self::$__dir__ = Path::realpath(__DIR__);
self::$__file__ = Path::realpath(__FILE__);
// load local config _filesconfig.php if exists
self::$localconfig = $this->load(self::$localconfigpath);
// create initial config array from default and localconfig
self::$config = array_replace(self::$default, self::$localconfig);
// set absolute storagepath, create storage dirs if required, and load, create or update storage config.php
$this->storage();
// at this point we must check if login is required or user is already logged in, and then merge user config
new Login();
// assign public real root path
self::$root = Path::realpath(self::get('root'));
// error if root path does not exist
if(!self::$root) U::error('root dir <b>' . self::get('root') . '</b> does not exist');
// storagepath can't be the same as root dir, because storage_path is excluded
if(self::$storagepath === self::$root) U::error('storage_path can\'t be the same as root');
// get server document root with normalized OS path
self::$document_root = Path::realpath($_SERVER['DOCUMENT_ROOT']);
// assign public $is_logged_in if username or password or X3 login (plugin)
self::$is_logged_in = self::get('username') || self::get('password');// || X3::login();
}
// public shortcut function to get config option Config::get('option')
public static function get($option){
return self::$config[$option];
}
// load a config file and trim values / returns empty array if file doesn't exist
private function load($path) {
if(empty($path) || !file_exists($path)) return [];
$config = include $path;
if(empty($config) || !is_array($config)) return [];
return array_map(function($v){
return is_string($v) ? trim($v) : $v;
}, $config);
}
// set storagepath from config, create dir if necessary
private function storage(){
// ignore storagepath and disable cache settings if storage_path is specifically set to FALSE
if(self::get('storage_path') === false) {
foreach (['cache', 'image_resize_cache', 'folder_preview_image'] as $key) self::$config[$key] = false;
return;
}
// shortcut to config storage_path
$path = rtrim(self::get('storage_path'), '\/');
// invalid config storage_path can't be empty or non-string
if(!$path || !is_string($path)) U::error('Invalid storage_path parameter');
// get request ?action if any, to determine if we attempt to make dirs and files on config construct
$action = U::get('action');
// if ?action=tests, check what dirs and files will get created, for tests output
if($action === 'tests') {
foreach (['', '/config', '/config/config.php', '/cache/images', '/cache/folders', '/cache/menu'] as $key) {
if(!file_exists($path . $key)) self::$created[] = $path . $key;
}
}
// only make dirs and config if main document (no ?action, except action tests)
$make = !$action || $action === 'tests';
// make storage path dir if it doesn't exist or return error
if($make) U::mkdir($path);
// store absolute storagepath
self::$storagepath = Path::realpath($path);
// error in case storagepath still doesn't seem to exist from realpath()
if(!self::$storagepath) U::error('storage_path does not exist and can\'t be created');
// absolute cache path shortcut
self::$cachepath = self::$storagepath . '/cache';
// assign storage config path (normally */_files/config/config.php), from where we load config and save options
self::$storageconfigpath = self::$storagepath . '/config/config.php';
// load storage config (normally _files/config/config.php) or return empty array
self::$storageconfig = $this->load(self::$storageconfigpath);
// if storage config is not empty, update config by merging default, storageconfig and localconfig
if(!empty(self::$storageconfig)) self::$config = array_replace(self::$default, self::$storageconfig, self::$localconfig);
// only make storage dirs and config.php if main document or ?action=tests
if(!$make) return;
// create required storage dirs if they don't exist / error on fail
foreach (['config', 'cache/images', 'cache/folders', 'cache/menu'] as $dir) U::mkdir(self::$storagepath . '/' . $dir);
// create or update config file if older than index.php
if(!file_exists(self::$storageconfigpath) || filemtime(self::$storageconfigpath) < filemtime(__FILE__)) self::save();
}
// save to config.php in storagepath (normally _files/config/config.php) or create new config.php if file doesn't exist
public static function save($options = []){
// merge array of parameters with current storageconfig, and intersect with default, to remove invalida/outdated options
$save = array_intersect_key(array_replace(self::$storageconfig, $options), self::$default);
// create exported array string with save values merged into default values, all commented out
$export = preg_replace("/ '/", " //'", var_export(array_replace(self::$default, $save), true));
// loop save options and un-comment options where values differ from default options (for convenience, only store differences)
foreach ($save as $key => $value) if($value !== self::$default[$key]) $export = str_replace("//'" . $key, "'" . $key, $export);
// write formatted config array to config (normally _files/config/config.php)
return @file_put_contents(self::$storageconfigpath, '<?php ' . PHP_EOL . PHP_EOL . '// CONFIG / https://www.files.gallery/docs/config/' . PHP_EOL . '// Uncomment the parameters you want to edit.' . PHP_EOL . 'return ' . $export . ';');
}
}
// class Login / check and manage login
class Login {
// vars
private $user; // config array for logged in user, will merge with main config
private $has_public_login; // public (default config) login exists / in this case, login is required
// start new login check process
public function __construct() {
// public (default config) login exists / in this case, login is required / also check X3:login() plugin
$this->has_public_login = Config::get('username') && Config::get('password') ? true : X3::login();
// check if there is any login, from default config or users, so we can check session and login attempt or show login form
if(!$this->has_public_login && !$this->users_dir()){
// unset session token in case it remains in any active session for some reason (probably shouldn't happen)
if(isset($_SESSION['token'])) unset($_SESSION['token']);
return;
}
// PHP session_start() or error
// check active sessions, session token on login attempt or assign session token on login form
if(session_status() === PHP_SESSION_NONE && !session_start()) U::error('Failed to initiate PHP session_start()', 500);
// check if browser is already logged in by session
if($this->is_logged_in()){
// allow ?logout=1 only if user is already logged in
if(U::get('logout')) return $this->form();
// merge user config and continue
return $this->login();
}
// ?login=1 displays login form, if user is not already logged in
// this only applies when login is not required !$this->has_public_login, else the login form will always display
if(U::get('login')) return $this->form();
// detect $_POST login attempt
if($this->is_login_attempt()) {
// on successful login, merge user config and continue
if($this->is_successful_login()) return $this->login();
// if default config is without login, serve request without login
} else if(!$this->has_public_login){
return;
}
// return error if request is an action (don't display login form)
if($this->action_request()) return;
// display form if not logged in or login failed attempt
$this->form();
}
// check if _files/users dir exists and return path
private function users_dir(){
return Config::$storagepath && file_exists(Config::$storagepath . '/users') ? Config::$storagepath . '/users' : false;
}
// check if user is already logged in by session
private function is_logged_in(){
// exit if session username or login hash is not set
if(!isset($_SESSION['username']) || !isset($_SESSION['login'])) return false;
// get user config from $_SESSION username
$this->user = $this->get_user($_SESSION['username']);
// logged in if user found login hash matches session login hash
// may fail if user is deleted or username/password/IP/user-agent/app-location changes
return $this->user && $this->equals($this->login_hash($this->user), $_SESSION['login']);
}
// detect login attempt
private function is_login_attempt(){
// on javascript fetch() from non-login interface, we must populate $_POST from php://input
if(U::get('action') === 'login' && empty($_POST)) $_POST = @json_decode(@trim(@file_get_contents('php://input')), true);
// is login attempt if $_POST['fusername']
return !!U::post('fusername');
}
// detect successful login attempt
private function is_successful_login(){
// login attempt if fusername, fpassword and token in $_POST and 'token' exists in $_SESSION
if(!U::post('fusername') || !U::post('fpassword') || !U::post('token') || !isset($_SESSION['token'])) return false;
// make sure $_SESSION token matches $_POST token
if(!$this->equals($_SESSION['token'], U::post('token'))) return false;
// get user config from $_POST username
$this->user = $this->get_user($_POST['fusername']);
// exit if can't find user or password doesn't match
if(!$this->user || !$this->passwords_match($this->user['password'], $_POST['fpassword'])) return false;
// store username in session
$_SESSION['username'] = $this->user['username'];
// store login hash specific to user, must match on active sessions
$_SESSION['login'] = $this->login_hash($this->user);
// successfull login
return true;
}
// successfully logged in by session or login attempt
private function login(){
// list of excluded user config options because they should be global or have no function for user or could cause harm
// you can add your own options here if you want to prevent some options from being changed per user
$user_exclude = [
'image_resize_dimensions', // should not change per user as it invalidates shared image cache
'image_resize_dimensions_retina', // should not change per user as it invalidates shared image cache
'image_resize_dimensions_allowed', // should not change per user as it invalidates shared image cache
'image_resize_quality', // should not change per user as it invalidates shared image cache
'image_resize_function', // should not change per user as it invalidates shared image cache
'image_resize_sharpen', // should not change per user as it invalidates shared image cache
'storage_path', // storage path is always global and must be defined in main config
'video_ffmpeg_path', // should be in global config
'imagemagick_path', // should be in global config
];
// merge user config into config object
Config::$config = array_replace(Config::$config, array_diff_key($this->user, array_flip($user_exclude)));
}
// get user config from login attempt or session
private function get_user($username){
// trim username just in case
$username = trim($username);
// create lowercase username for case-insensitive comparison
$lower_username = $this->lower($username);
// user equals default config user / return username/password array to verify password or session login
if($this->lower(Config::get('username')) === $lower_username) return [
'username' => Config::get('username'),
'password' => Config::get('password')
];
// exit it _files/users dir doesn't exist
if(!$this->users_dir()) return false;
// check if user config exists at _files/users/$username/config.php without making case-insensitive lookup
// this should apply in most cases when username is input in identical case or from $_SESSION['username']
// Mac OS will find user case-insensitive, but that's fine as it doesn't then matter how $_SESSION['username'] is stored
$user = $this->get_user_config($username);
if($user) return $user;
// loop user dirs and make case-insensitive username comparison
foreach (glob($this->users_dir() . '/*', GLOB_ONLYDIR|GLOB_NOSORT) as $dir) {
$arr = explode('/', $dir); // get basename, better than basename() in case of multibyte chars
$dirname = end($arr); // get basename, better than basename() in case of multibyte chars
// case-insensitive username matches user dir, get user config from $dirname with case in tact (for $_SESSION['username'])
if($lower_username === $this->lower($dirname)) return $this->get_user_config($dirname);
}
}
// get user config.php file for a specific user $dirname
private function get_user_config($dirname){
$user = U::uinclude("users/$dirname/config.php"); // return user config array
if(!$user) return; // exit if not found
// error if the user array does not contain password *required
if(empty($user['password'])) return $this->error('User does not have valid password');
// return user array merged with username, which is used for $_SESSION['login'] login_hash()
return array_replace($user, ['username' => $dirname]);
}
// creates a login hash unique for username/password/IP/user-agent/app-location
private function login_hash($user){
return md5($user['username'] . $user['password'] . $this->ip() . $this->server('HTTP_USER_AGENT') . __FILE__);
}
// compares strings with more secure hash_equals() function (PHP >= 5.6)
private function equals($secret, $user){
return function_exists('hash_equals') ? hash_equals($secret, $user) : $secret === $user;
}
// match passwords using password_verify() if password is encrypted else use plain equality matching for non-encrypted passwords
private function passwords_match($stored, $posted){
if(password_get_info($stored)['algoName'] === 'unknown') return $this->equals($stored, $posted);
return password_verify($posted, $stored);
}
// get client IP for login hash matching
private function ip(){
foreach(['HTTP_CLIENT_IP','HTTP_X_FORWARDED_FOR','HTTP_X_FORWARDED','HTTP_FORWARDED_FOR','HTTP_FORWARDED','REMOTE_ADDR'] as $key){
$ip = explode(',', $this->server($key))[0];
if($ip && filter_var($ip, FILTER_VALIDATE_IP)) return $ip;
}
return ''; // return empty string if nothing found
}
// get $_SERVER parameters helpers
private function server($str){
return isset($_SERVER[$str]) ? $_SERVER[$str] : '';
}
// lowercase username for case-insensitive username validation uses mb_strtolower() if function exists
private function lower($str){
return function_exists('mb_strtolower') ? mb_strtolower($str) : strtolower($str);
}
// check if request is an action, in which case we return error instead of the form
private function action_request(){
// exit if !action (or action is "tests", which requires login from the form)
if(!U::get('action') || U::get('action') === 'tests') return false;
// return json error if request is POST
if($_SERVER['REQUEST_METHOD'] === 'POST') return Json::error('login');
// login error with login link
U::error('Please <a href="' . strtok($_SERVER['REQUEST_URI'], '?') . '">login</a> to continue', 401);
}
// login page / output form html and exit
private function form() {
// get form alert caused by logout, invalid session or incorrect login, before we destroy sessions vars
$alert = $this->get_form_alert();
// destroy login-specific session vars on logout or if they are invalid / session_unset()
foreach (['username', 'login'] as $key) unset($_SESSION[$key]);
// assign session token to match on login attempt for basic login security
if(!isset($_SESSION['token'])) $_SESSION['token'] = bin2hex(function_exists('random_bytes') ? random_bytes(32) : openssl_random_pseudo_bytes(32));
// get login form page header
U::html_header('Login', 'page-login');
// login page html
// block simple bots by injecting form via javascript, add action and method on submit
?><body class="page-login-body">
<article class="login-container"></article>
</body>
<script>
const url = location.pathname + (location.search || '').replace(/(logout|login)=(1|true)(&?|$)/g, '').replace(/(\?|&)$/, '');
document.querySelector('.login-container').innerHTML = `
<h1>Login</h1>
<?php echo $alert; ?>
<form class="login-form">
<input type="text" class="input" name="fusername" placeholder="Username" required autofocus spellcheck="false" autocorrect="off" autocapitalize="off" autocomplete="off">
<input type="password" class="input" name="fpassword" placeholder="Password" required spellcheck="false" autocomplete="off">
<input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>">
<div class="login-form-buttons">
<?php if(!$this->has_public_login) echo '<a href="${ url }" class="button button-secondary login-cancel-button">Cancel</a>'; ?>
<button type="submit" class="button login-button">Login</button>
</div>
</form>`;
document.querySelector('.login-form').addEventListener('submit', (e) => {
document.body.classList.add('form-loading');
e.currentTarget.action = url;
e.currentTarget.method = 'post';
}, false);
</script>
</html><?php exit; // end form and exit
}
// get alert string for login form
private function alert($text, $type = 'danger'){
return '<div class="alert alert-' . $type . '" role="alert">' . $text . '</div>';
}
// outputs an alert in login form on logout, incorrect login or session ID mismatch
private function get_form_alert(){
// ?logout=1 show logout text if was logged in
if(U::get('logout')) return isset($_SESSION['username']) ? $this->alert('You are now logged out', 'warning') : '';
// must have been logged in, but session expired or username/password/IP/user-agent/app-location changed
if(isset($_SESSION['username'])) return $this->alert('You were logged out', 'warning'); // probably shouldn't happen
// failed login attempt, normally wrong username or password, although could be invalid login token
if(isset($_POST['fusername'])) return $this->alert('Incorrect login', 'danger');
// no alert in form
return '';
}
}
// class U / static utility functions (short U because I want compact function access)
class U {
// get file basename / basically just a wrapper in case it needs to be refined on some servers
public static function basename($path){
return basename($path); // because setlocale(LC_ALL,'en_US.UTF-8')
// OPTIONAL: replace basename() which may fail on UTF-8 chars if locale != UTF8
//$arr = explode('/', str_replace('\\', '/', $path));
//return end($arr);
}
// get mime type for file
public static function mime($path){
if(function_exists('mime_content_type')) return mime_content_type($path);
if(function_exists('finfo_file')) return finfo_file(finfo_open(FILEINFO_MIME_TYPE), $path);
return false;
}
// get file extension with options to lowercase and include dot
public static function extension($path, $lowercase = false, $dot = false) {
$ext = pathinfo($path, PATHINFO_EXTENSION);
if(!$ext) return '';
if($lowercase) $ext = strtolower($ext);
if($dot) $ext = '.' . $ext;
return $ext;
}
// glob() wrapper for reading paths / escape [brackets] in folder names (it's complicated)
public static function glob($path, $dirs_only = false){
if(preg_match('/\[.+]/', $path)) $path = str_replace(['[',']', '\[', '\]'], ['\[','\]', '[[]', '[]]'], $path);
return @glob($path, $dirs_only ? GLOB_NOSORT|GLOB_ONLYDIR : GLOB_NOSORT);
}
// get $_POST parameter or false
public static function post($param){
return isset($_POST[$param]) && !empty($_POST[$param]) ? $_POST[$param] : false;
}
// get $_GET parameter or false
public static function get($param){
return isset($_GET[$param]) && !empty($_GET[$param]) ? $_GET[$param] : false;
}
// make dir unless it already exists, error if fail
public static function mkdir($path){
if(!file_exists($path) && !mkdir($path, 0777, true)) U::error('Failed to create ' . $path, 500);
}
// helper function to check for and include various files html, php, css and js from storage_path _files/*
public static function uinclude($file){
if(!Config::$storagepath) return;
$path = Config::$storagepath . '/' . $file;
if(!file_exists($path)) return;
$ext = U::extension($path);
if(in_array($ext, ['html', 'php'])) return include $path;
$src = Path::urlpath($path); // get urlpath for public resource
if(!$src) return; // return if storagepath is non-public (not inside document root)
$src .= '?' . filemtime($path); // append modified time of file, so updated resources don't get cached in browser
if($ext === 'js') echo '<script src="' . $src . '"></script>';
if($ext === 'css') echo '<link href="' . $src . '" rel="stylesheet">';
}
// attempt to ini_get($directive)
public static function ini_get($directive){
$val = function_exists('ini_get') ? @ini_get($directive) : false;
return is_string($val) ? trim($val) : $val;
}
// get php ini value to bytes
public static function ini_value_to_bytes($directive) {
$val = U::ini_get($directive);
if(empty($val) || !is_string($val)) return 0;
if(function_exists('ini_parse_quantity')) return @ini_parse_quantity($val) ?: 0;
if(!preg_match('/^(\d+)([G|M|K])?$/i', trim($val), $m)) return 0;
if(!isset($m[2])) return (int) $m[1];
return (int) $m[1] *= ['G' => 1024 * 1024 * 1024, 'M' => 1024 * 1024, 'K' => 1024][strtoupper($m[2])];
}
// get memory limit in MB, if available, so we can calculate memory for image resize operations
public static function get_memory_limit_mb() {
$val = U::ini_value_to_bytes('memory_limit');
return $val ? $val / 1024 / 1024 : 0; // convert bytes to M
}
// get exec app path (ffmpeg, imagemagick)
private static function exec_app_path($app_path){
// external thumbnail apps required load_images and image_resize_cache to be enabled
foreach (['load_images', 'image_resize_cache'] as $key) if(!Config::get($key)) return;
// exec() must be available to access command-line tools
if(!function_exists('exec')) return;
// path to ffmpeg in command-line is normally just 'ffmpeg', but escapeshellarg() in case using absolute path
$path = escapeshellarg(Config::get($app_path));
//$path = '"' . str_replace('"', '\"', Config::get($app_path)) . '"'; // <- if path contains Chinese chars
// attempt to run -version function on app and return the path or false on fail
return @exec($path . ' -version') ? $path : false;
}
// detect FFmpeg availability for video thumbnails and return path or false / https://ffmpeg.org/
public static function ffmpeg_path(){
// below config options must be enabled for FFmpeg to apply
foreach (['video_thumbs', 'video_ffmpeg_path'] as $key) if(!Config::get($key)) return;
// return imagemagick path for exec()
return U::exec_app_path('video_ffmpeg_path');
}
// detect ImageMagick availability for PDF thumbnails and return path or false / https://imagemagick.org/
public static function imagemagick_path(){
// below config options must be enabled for FFmpeg to apply
foreach (['pdf_thumbs', 'imagemagick_path'] as $key) if(!Config::get($key)) return;
// return imagemagick path for exec()
return U::exec_app_path('imagemagick_path');
}
// readfile() wrapper function to output file with tests, clone option and headers
public static function readfile($path, $mime, $message = false, $cache = false, $clone = false){
if(!$path || !file_exists($path)) return false;
if($clone && @copy($path, $clone)) U::message('cloned to ' . U::basename($clone));
U::header($message, $cache, $mime, filesize($path), 'inline', U::basename($path));
if(!is_readable($path) || readfile($path) === false) U::error('Failed to read file ' . U::basename($path), 400);
exit;
}
// return an array of supported image resize types / used by Javascript to determine what resized image types can be requested
public static function resize_image_types(){
return array_merge(['jpeg', 'jpg', 'png', 'gif'], array_filter(['webp', 'bmp', 'avif'], function($type){
return function_exists('imagecreatefrom' . $type);
}));
}
// common error response with response code, error message and json option
// 400 Bad Request, 403 Forbidden, 401 Unauthorized, 404 Not Found, 500 Internal Server Error
public static function error($error = 'Error', $http_response_code = false, $is_json = false){
if($is_json) return Json::error($error);
if($http_response_code) http_response_code($http_response_code);
U::header("[ERROR] $error", false);
exit("<h3>Error</h3>$error.");
}
// get dirs hash based on various options for cache paths and browser localstorage / with cached response
private static $dirs_hash;
public static function dirs_hash(){
if(self::$dirs_hash) return self::$dirs_hash;
return self::$dirs_hash = substr(md5(Config::$document_root . Config::$__dir__ . Config::$root . Config::$version . Config::get('cache_key') . U::image_resize_cache_direct() . Config::get('files_exclude') . Config::get('dirs_exclude')), 0, 6);
}
// check if image_resize_cache_direct is enabled for direct access to resized image cache files / with cached response
private static $image_resize_cache_direct;
public static function image_resize_cache_direct(){
if(isset(self::$image_resize_cache_direct)) return self::$image_resize_cache_direct;
return self::$image_resize_cache_direct = Config::get('image_resize_cache_direct') && !Config::$is_logged_in && Config::get('load_images') && Config::get('image_resize_cache') && Config::get('image_resize_enabled') && Path::is_within_docroot(Config::$storagepath);
}
// image_resize_dimensions_retina (serve larger dimension resized images for HiDPI screens) with cached response
private static $image_resize_dimensions_retina;
public static function image_resize_dimensions_retina(){
if(isset(self::$image_resize_dimensions_retina)) return self::$image_resize_dimensions_retina;
$retina = intval(Config::get('image_resize_dimensions_retina'));
return self::$image_resize_dimensions_retina = $retina > Config::get('image_resize_dimensions') ? $retina : false;
}
// get common html header for main document and login page
public static function html_header($title, $class){
?>
<!doctype html><!-- www.files.gallery -->
<html class="<?php echo $class; ?>" data-theme="contrast">
<script>
let theme = (() => {
try {
return localStorage.getItem('files:theme');
} catch (e) {
return false;
};
})() || (matchMedia('(prefers-color-scheme:dark)').matches ? 'dark' : 'contrast');
if(theme !== 'contrast') document.documentElement.dataset.theme = theme;
</script>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<link rel="apple-touch-icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMAAAADABAMAAACg8nE0AAAAD1BMVEUui1f///9jqYHr9O+fyrIM/O8AAAABIklEQVR42u3awRGCQBBE0ZY1ABUCADQAoEwAzT8nz1CyLLszB6p+B8CrZuDWujtHAAAAAAAAAAAAAAAAAACOQPPp/2Y0AiZtJNgAjTYzmgDtNhAsgEkyrqDkApkVlsBDsq6wBIY4EIqBVuYVFkC98/ycCkr8CbIr6MCNsyosgJvsKxwFQhEw7APqY3mN5cBOnt6AZm/g6g2o8wYqb2B1BQcgeANXb0DuwOwNdKcHLgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAeA20mArmB6Ugg0NsCcP/9JS8GAKSlVZMBk8p1GRgM2R4jMHu51a/2G1ju7wfoNrYHyCtUY3zpOthc4MgdNy3N/0PruC/JlVAwAAAAAAAAAAAAAAABwZuAHuVX4tWbMpKYAAAAASUVORK5CYII=">
<meta name="mobile-web-app-capable" content="yes">
<title><?php echo $title; ?></title>
<?php U::uinclude('include/head.html'); ?>
<link href="<?php echo U::assetspath(); ?>files.photo.gallery@<?php echo Config::$version ?>/css/files.css" rel="stylesheet">
<?php U::uinclude('css/custom.css'); ?>
</head>
<?php
}
// output file as download using correct headers and readfile() / used to download zip and force download single files
public static function download($file, $message, $mime, $filename){
U::header($message, false, $mime, filesize($file), 'attachment', $filename);
while (ob_get_level()) ob_end_clean();
return readfile($file) !== false;
}
// assign assets url for plugins, Javascript, CSS and languages, defaults to CDN https://www.jsdelivr.com/
// if you want to self-host assets: https://www.files.gallery/docs/self-hosted-assets/
private static $assetspath;
public static function assetspath(){
if(self::$assetspath) return self::$assetspath;
return self::$assetspath = Config::get('assets') ? rtrim(Config::get('assets'), '/') . '/' : 'https://cdn.jsdelivr.net/npm/';
}
// response headers
// cache time 1 year for cacheable assets / can be modified if you really need to
public static $cache_time = 31536000;
// array of messages to go into files-response header
private static $messages = [];
// add messages (string or array) to files-response header
public static function message($items = []){
self::$messages = array_merge(self::$messages, is_string($items) ? [$items] : array_filter($items));
}
// set request response headers, including files-message header for diagnosing response
public static function header($message, $cache = null, $type = false, $length = 0, $disposition = false, $filename = ''){
// prepend main $message to $messages array
if($message) array_unshift(self::$messages, $message);
// append PHP response time to $messages
if(isset($_SERVER['REQUEST_TIME_FLOAT'])) self::$messages[] = round(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], 3) . 's';
// append memory usage to $messages
if(function_exists('memory_get_peak_usage')) self::$messages[] = round(memory_get_peak_usage() / 1048576, 1) . 'M';
// assign files-message header with all $messages
header('files-response: ' . implode(' | ', self::$messages));
// cache response headers
if($cache){
$shared = Config::$is_logged_in ? 'private' : 'public'; // private or shared cache depending on login
header('expires: ' . gmdate('D, d M Y H:i:s \G\M\T', time() + self::$cache_time));
header('cache-control: ' . $shared . ', max-age=' . self::$cache_time . ', s-maxage=' . self::$cache_time . ', immutable');
// no cache response headers if specifically set to false (if null, don't do anything)
} else if($cache === false){
header('cache-control: no-store, must-revalidate');
}
// assign content-type header
if($type) header("content-type: $type");
// assign content-length header / only assigned when reading actual files on disk when we can get filesize()
if($length) header("content-length: $length");
// assign content-disposition when reading files on disk, assigned to either 'inline' or 'attachment'
if($disposition) header('content-disposition: ' . $disposition . '; filename="' . addslashes($filename) . '"');
}
}
// class Path / various static functions to convert and validate file paths
class Path {
// returns resolved absolute paths and normalizes slashes across OS / returns false if file does not exist
public static function realpath($path){
$realpath = realpath($path);
return $realpath ? str_replace('\\', '/', $realpath) : false;
}
// get absolute path by appending relative path to root path (does not resolve symlinks)
public static function rootpath($relpath){
return Config::$root . (strlen($relpath) ? "/$relpath" : ''); // check paths with strlen() in case dirname is '0'
}
// get relative path from full root path / used as internal reference and in query ?path/path
public static function relpath($path){
return trim(substr($path, strlen(Config::$root)), '\/');
}
// determines if root is accessible by URL and returns the root url path, which in turn allows files to be accessible by url
private static function get_root_url_path(){
// custom root url path if `root_url_path` is assigned
if(is_string(Config::get('root_url_path'))) return Config::get('root_url_path');
// if root is within application dir (index.php), we can serve application-relative path
//if(self::is_within_path(Config::$root, Config::$__dir__)) return substr(Config::$root, strlen(Config::$__dir__) + 1);
// if root is within application dir (index.php), we can serve application-relative path
if(self::is_within_path(Config::$root, Config::$__dir__)) {
// if root is same as app dir (quite common), return empty relative path ''
if(Config::$root === Config::$__dir__) return '';
// return relative path from app to root
return substr(Config::$root, strlen(Config::$__dir__) + 1);
}
// if root is within document root, serve root-relative path
if(self::is_within_docroot(Config::$root)) return substr(Config::$root, strlen(Config::$document_root));
// exit unless root is a symlink
// at this point, when `root` resolves outside of document root, we have to assume it's not directly accessible by url
// if you know your `root` is accessible by url somehow (nginx/apache/symlink), you can use the `root_url_path` config option
if(!is_link(Config::get('root'))) return false;
// in case someone wants to entirely disable resolving url path from root symlinks that point outside of document root
if(Config::get('root_url_path') === FALSE) return false;
// SYMLINK helpers
// because it's useful to point root to symlinks that might be in, but resolve outside document root
// assign $root shortcut just to make things more readable
$root = Config::get('root');
// don't mess around with absolute paths that point to symlinks outside of document root, as it's pointless and complicated
if(preg_match('/:\/|^\/|^\\\/', $root)) return false;
// to create a base app or root relative path, we need to trim orders
$trimmed_root = trim($root, './');
// check if root traverses up into parent dirs somewhere, and count traversal depth
$root_parent_depth = substr_count($root, '..');
// if root does not traverse parent dirs, we can assume it's relative to app (index.php)
// re-check if trimmed relative path exists and return app relative path
if(!$root_parent_depth) return file_exists($trimmed_root) ? $trimmed_root : false;
// attempt to assemble /root-relative path if root traverses up into parent dirs
// must check PHP_SELF for comparison and PHP > 7
if(!isset($_SERVER['PHP_SELF']) || version_compare(PHP_VERSION, '7.0.0') < 0) return false;
// PHP_SELF determines application root url path, so we can check root parent compared to application path
$php_self = $_SERVER['PHP_SELF'];
// get relative url depth of self (-1 because includes trailing slash with filename /path/index.php)
$php_self_depth = substr_count($php_self, '/') - 1;
// exit if root parent depth extends beyond php self depth
if($root_parent_depth > $php_self_depth) return false;
// assemble root-relative url path by traversing php_self
return rtrim(dirname($php_self, $root_parent_depth + 1), '/') . '/' . $trimmed_root;
}
// create url path for a file from $root_url_path + file relative path / used for dir data, get_downloadables and uploads
private static $root_url_path;
public static function rooturlpath($rel){
// $root_url_path only needs to be assigned once when required
if(!isset(self::$root_url_path)) self::$root_url_path = self::get_root_url_path();
// return false if if $root_url_path is false
if(self::$root_url_path === FALSE) return false; //return self::urlpath($path);
// return $root_url_path if relative path is empty (would be the root dir)
if(!$rel) return self::$root_url_path;
// assemble url path for file from $root_url_path and $rel
return self::$root_url_path . (in_array(self::$root_url_path, ['', '/']) ? '' : '/') . $rel;
}
// get public url path relative to script or server document root
public static function urlpath($path){
// return if item is not within server document root, because it can't be accessed by www url
if(!self::is_within_docroot($path)) return false;
// if item is within application dir, we can return relative path
if(self::is_within_path($path, Config::$__dir__)) return $path === Config::$__dir__ ? '.' : substr($path, strlen(Config::$__dir__) + 1);
// return root-relative path
return $path === Config::$document_root ? '/' : substr($path, strlen(Config::$document_root));
}
// determines if a path is equal to or inside another path / append slash so that path/dirx/ does not match path/dir/
public static function is_within_path($path, $root){
return $path && strpos($path . '/', $root . '/') === 0;
}
// determines if path is within server document root (so we can determine if it's accessible by URL)
public static function is_within_docroot($path){
return $path && self::is_within_path($path, Config::$document_root);
}
// calculate path for image resize cache
public static function imagecachepath($path, $image_resize_dimensions, $filesize, $filemtime){
return Config::$cachepath . '/images/' . substr(md5($path), 0, 6) . ".$filesize.$filemtime.$image_resize_dimensions.jpg";
}
// determines if relative path is valid, and returns full rootpath or false if invalid
public static function valid_rootpath($relpath, $is_dir = false){
// invalid if path is false (might be previously unresolved)
if($relpath === false) return;
// invalid if is file and path is empty (path can be '' empty string for root dir)
if(!$is_dir && empty($relpath)) return;
// relative path should never start or end with slash/
if(preg_match('/^\/|\/$/', $relpath)) return;
// get root path from relative path
$rootpath = self::rootpath($relpath);
// realpath may differ from rootpath if symlinked or if relpath contains parent ../ paths
$realpath = self::realpath($rootpath);
// invalid if file does not exist
if(!$realpath) return;
// additional security checks if realpath differs from rootpath, and realpath is no longer within root
// blocks potential abuse of relative paths like ?path/../../../../dir
if($realpath !== $rootpath && !self::is_within_path($realpath, Config::$root)) {
if(strpos(($is_dir ? $relpath : dirname($relpath)), ':') !== false) return; // dir may not contain ':'
if(strpos($relpath, '..') !== false) return; // path may not contain '..'
//if(self::is_exclude($realpath, $is_dir, true)) return; // check is_exclude also on realpath / seems pointless ...
}
// is invalid
if(!is_readable($realpath)) return; // not readable
if($is_dir && !is_dir($realpath)) return; // invalid dir
if(!$is_dir && !is_file($realpath)) return;// invalid file
if(self::is_exclude($rootpath, $is_dir)) return; // rootpath is excluded
// return full path
return $rootpath;
}
// determine if path should be excluded from displaying in the gallery
public static function is_exclude($path = false, $is_dir = true, $symlinked = false){
// is not excluded if empty or path is root
if(!$path || $path === Config::$root) return;
// exclude relative paths that start with _files* (reserved for hidden items)
if(strpos('/' . self::relpath($path), '/_files') !== false) return true;
// exclude Files Gallery PHP application name (normally "index.php" but could be renamed)
if($path === Config::$__file__) return true;
// exclude symlinks if symlinks not allowed (symlinks might be sensitive)
if($symlinked && !Config::get('allow_symlinks')) return true;
// exclude Files Gallery storage_path (normally _files dir relative to PHP file)
if(Config::$storagepath && self::is_within_path($path, Config::$storagepath)) return true;
// exclude if dir or file's parent dir is excluded by config dirs_exclude
if(Config::get('dirs_exclude')) {
// dir to check is path or parent dir if file
$dirname = $is_dir ? $path : dirname($path);
// check if dir matches dirs_exclude, unless dir is root (root dir can't be excluded)
if($dirname !== Config::$root && preg_match(Config::get('dirs_exclude'), self::relpath($dirname))) return true;
}
// exclude file
if(!$is_dir){
// get file name
$filename = U::basename($path);
// make sure file is not local config file