-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathindex.php
More file actions
4334 lines (3406 loc) · 195 KB
/
index.php
File metadata and controls
4334 lines (3406 loc) · 195 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
/* Files Gallery 0.5.1
---
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 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 CleanCache / cleans invalid and expired cache files from the _files/cache/* dirs at specific intervals or manually
class Document / creates the main Files Gallery document response
*/
// class Config / constructor and static methods to access config options
class Config {
// config defaults
// 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)
public static $default = [
'root' => '',
'root_url_path' => null,
'root_lock' => 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_use_imagemagick' => false,
'image_resize_cache' => true,
'image_resize_cache_use_dir' => false,
'image_resize_dimensions' => 320,
'image_resize_dimensions_retina' => 480,
'image_resize_dimensions_allowed' => '',
'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,
'clean_cache_interval' => 7,
'clean_cache_allow_manual' => false,
'image_cache_file' => 'cache.txt',
'image_cache_max_last_access_time' => 90,
'image_cache_validate_time' => true,
'storage_path' => '_files',
'files_include' => '',
'files_exclude' => '',
'dirs_include' => '',
'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_settings' => 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',
'ffmpeg_path' => 'ffmpeg',
'imagemagick_path' => 'convert',
'imagemagick_prefer_imagick' => true,
'imagemagick_image_types' => 'heif, heic, tiff, tif, psd, dng',
'use_google_docs_viewer' => false,
'lang_default' => 'en',
'lang_auto' => true,
'index_cache' => false,
];
// global application variables created on new Config()
public static $version = '0.5.1'; // 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 $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();
// get server document root with normalized OS path
self::$document_root = Path::realpath($_SERVER['DOCUMENT_ROOT']);
// install.php - allow edit settings and create users from interface temporarily when file is named "install.php"
// useful when installing Files Gallery, allows editing settings and creating users without having to modify config.php manually
// remember to rename the file back to index.php once you have edited settings and/or created users.
if(U::basename(__FILE__) === 'install.php') self::$config['allow_settings'] = true;
// at this point we must check if login is required or user is already logged in, and then merge user config
new Login();
// assign root realpath after login user is resolved
self::$root = Path::valid_root(self::get('root'));
// error if root path does not exist
if(!self::$root) U::error('Invalid root dir "' . self::get('root') . '"');
// shortcut option `allow_all` allows all file actions (except settings, check_updates, tests, tasks)
if(self::get('allow_all')) foreach (['upload', 'delete', 'rename', 'new_folder', 'new_file', 'duplicate', 'text_edit', 'zip', 'unzip', 'move', 'copy', 'download', 'mass_download', 'mass_copy_links'] as $k) self::$config['allow_'.$k] = true;
}
// public shortcut function to get config option Config::get('option')
public static function get($option){
return self::$config[$option];
}
// public get config comma-delimited string option as array
public static function get_array($option) {
$str = self::$config[$option];
return !empty($str) && is_string($str) ? array_map('trim', explode(',', $str)) : [];
}
// 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("/ '/", " //'", U::var_export(array_replace(self::$default, $save)));
// 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 . '// 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
public static $is_logged_in; // user is logged in flag
public static $has_public_login; // public (default config) login exists / in this case, login is required
public static $is_default_user; // is default config user (login by username and password from default config.php)
// start new login check process
public function __construct() {
// public (default config) login exists / in this case, login is required
self::$has_public_login = Config::get('username') && Config::get('password') ? true : false;
// check if there is any login, from default config or users, so we can check session and login attempt or show login form
if(!self::$has_public_login && !self::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;
}
// un-comment below to increase login session cookie lifetime to 24 hours (or change it)
// session_set_cookie_params(86400);
// 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);
// un-comment below to attempt to extend session timeout in browser and server
// setcookie(session_name(), session_id(), time() + 3600); // default 0, means logout on browser session (window close)
// ini_set('session.gc_maxlifetime', '3600'); // default '1440'
// assign CSRF security $_SESSION['token'] / used in login form to compare with login attempt, and forwarded to the app (JS) so it knows there is login / could be used in all action requests also, but I see the point in that
$this->set_session_token();
// detect $_POST login attempt
if($this->is_login_attempt()) {
// on successful login, merge user config and login
if($this->is_successful_login()) return $this->login();
// check if browser is already logged in by session
} else if($this->is_logged_in()){
// ?logout=1 parameter to logout can only apply if user is already logged in
if(U::get('logout')) {
// we can return and serve request without login if default config does not require login
// un-comment the below if you want to redirect to non-login version on logout, instead of showing the login form
// if(!self::$has_public_login) return $this->clear_session();
// logout displays login form
return $this->form();
}
// merge user config and login
return $this->login();
// if not logged in and default config does not require login (no username or password)
} else if(!self::$has_public_login) {
// ?login=1 displays login form when default config does not require login
if(U::get('login')) {
// remove $_SESSION['username'] just in case user was removed while session remains
if(isset($_SESSION['username'])) unset($_SESSION['username']);
// serve request without login if default config does not require login
} else 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
public static function users_dir(){
return Config::$storagepath && file_exists(Config::$storagepath . '/users') ? Config::$storagepath . '/users' : false;
}
// get usernames from user_dirs()
public static function get_usernames(){
return array_map(function($path){
$arr = explode('/', $path); // get basename, better than basename() in case of multibyte chars
return end($arr); // get basename, better than basename() in case of multibyte chars
}, self::users_dir() ? glob(self::users_dir() . '/*', GLOB_ONLYDIR|GLOB_NOSORT) : []);
}
// assign CSRF security $_SESSION['token']
private function set_session_token(){
if(isset($_SESSION['token'])) return; // token already set
$_SESSION['token'] = bin2hex(function_exists('random_bytes') ? random_bytes(32) : openssl_random_pseudo_bytes(32));
}
// 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 = [
'root_lock', // should be global and pre-assiged in _filesconfig.php
'image_resize_use_imagemagick', // should be global
'image_resize_cache_use_dir', // should be global
'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
'image_cache_file', // should be global
'image_cache_max_last_access_time', // should be global
'image_cache_validate_time', // should be global
'storage_path', // storage path is always global and must be defined in main config
'ffmpeg_path', // should be global
'imagemagick_path', // should be global
'index_cache', // should be global / not available for logged in users anyway
];
// we are hereby logged in
self::$is_logged_in = true;
// merge user config into config object
Config::$config = array_replace(Config::$config, array_diff_key($this->user, array_flip($user_exclude)));
}
// clear login-specific session vars, essentially logging out the user
private function clear_session(){
foreach (['username', 'login'] as $key) unset($_SESSION[$key]);
}
// 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) {
self::$is_default_user = true; // is default config user
return [
'username' => Config::get('username'),
'password' => Config::get('password')
];
}
// exit it _files/users dir doesn't exist
if(!self::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 (self::get_usernames() as $username) {
// case-insensitive username matches user dir, get user config from $dirname with case in tact (for $_SESSION['username'])
if($lower_username === $this->lower($username)) return $this->get_user_config($username);
}
}
// 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()
$this->clear_session();
// get login form page header
U::html_header('Login', 'page-login');
// login page html / check language and render form via javascript (blocks simple bots)
?><body class="page-login-body body-loading"></body>
<script>
// get search parameter
const search = location.search || '';
// get action submit url but remove ?login and ?logout parameters
const url = location.pathname + search.replace(/(logout|login)=(1|true)(&?|$)/g, '').replace(/(\?|&)$/, '') + location.hash;
// history replace ?logout=1 in url to prevent navigating to ?logout=1 from browser back button
if(search.match(/logout=(1|true)/)) history.replaceState(null, '', url);
// Javascript Login class checks language and renders form
class Login {
// available languages
langs = ['ar', 'bg', 'cs', 'da', 'de', 'en', 'el', 'es', 'et', 'fi', 'fr', 'hu', 'id', 'it', 'ja', 'ko', 'ms', 'nl', 'no', 'pl', 'pt', 'ro', 'ru', 'sk', 'sl', 'sv', 'th', 'tr', 'uk', 'zh'];
// language object empty (English) by default
lang = {};
// render form
render(lang){
// re-assign lang object if lang loaded or assigned from localStorage
if(lang) this.lang = lang;
// remove loading speinner
document.body.classList.remove('body-loading');
// inject form
document.body.insertAdjacentHTML('afterBegin', `
<article class="login-container">
<h1 class="login-header">${ this.getlang('login') }</h1>
<?php echo $alert; ?>
<form class="login-form" onsubmit="document.body.classList.add('form-loading')" method="post" action="${ url }">
<input type="text" class="input" name="fusername" placeholder="${ this.getlang('username') }" required autofocus spellcheck="false" autocorrect="off" autocapitalize="off" autocomplete="off">
<input type="password" class="input" name="fpassword" placeholder="${ this.getlang('password') }" required spellcheck="false" autocomplete="off">
<input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>">
<div class="login-form-buttons">
<button type="submit" class="button login-button">${ this.getlang('login') }</button>
<?php if(!self::$has_public_login) { ?><a href="${ url }" class="button button-secondary login-cancel-button" onclick="document.body.classList.add('form-loading')">${ this.getlang('cancel') }</a><?php } ?>
</div>
</form>
</article>`);
}
// get language text Capitalized
getlang(str){
let s = this.lang[str] || str;
return s[0].toUpperCase() + s.slice(1);
}
// login constructor, get language then render form
constructor(){
// get ?lang= url parameter
let param = 'URLSearchParams' in window ? new URLSearchParams(location.search).get('lang') : 0;
// get language code from 1. url param ?lang=xX, 2. localStorage, 3. navigator.languages[], 4. lang_default, 5. English
let lang_code = [
param,
param !== 'reset' ? storage('files:lang:current') : 0,
<?php if(Config::get('lang_auto')) { ?>...(navigator.languages ? navigator.languages : [navigator.language || '']).map(l => l.toLowerCase().split('-')[0]),<?php } ?>
'<?php echo Config::get('lang_default'); ?>'
].find(l => l && this.langs.includes(l)) || 'en';
// render form if language is English
if(lang_code === 'en') return this.render();
// check if we have language already loaded into localStorage / try-catch in case localStorage is not json
let local = storage(`files:lang:${ lang_code }`);
if(local) try { return this.render(JSON.parse(local)) } catch (e) {};
// load json language file and render form with loaded language file / on error, render default English
fetch(`<?php echo U::assetspath() ?>smooth-files-gallery@<?php echo Config::$version ?>/lang/${ lang_code }.json`)
.then(response => response.ok ? response.json() : 0)
.then(json => {
this.render(json);
if(json) storage(`files:lang:${ lang_code }`, JSON.stringify(json));
}).catch(e => this.render());
}
}
// start login load language and render form
new Login();
</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">${ this.getlang("' . $text . '") }</div>';
}
// outputs an alert in login form on logout, incorrect login or session ID mismatch
private function get_form_alert(){
// failed login attempt, normally wrong username or password, although could be invalid login token
if(isset($_POST['fusername'])) return $this->alert('invalid login', 'danger');
// logged out by ?logout=1 or cookie/session expired or username/password/IP/user-agent/app-location changed
return isset($_SESSION['username']) ? $this->alert('you were logged out', 'warning') : '';
}
}
// 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
// cache result $memory_limit_mb because it runs in image file loops
private static $memory_limit_mb;
public static function get_memory_limit_mb() {
if(isset(self::$memory_limit_mb)) return self::$memory_limit_mb;
$val = U::ini_value_to_bytes('memory_limit');
return self::$memory_limit_mb = $val ? $val / 1024 / 1024 : 0; // convert bytes to M
}
// get and validate path for exec() apps imagemagick and ffmpeg
public static function app_path($app){
$path = Config::get($app . '_path');
if(!$path || !function_exists('exec')) return false;
$escaped = escapeshellarg($path);
if(!@exec("$escaped -version", $output, $result_code) || $result_code) return false;
// upgrade to the newer 'magick' command if imagemagick_path is 'convert' and we detect ImageMagick 7
if($path === 'convert' && strpos($output[0], 'ImageMagick 7') !== false) return "'magick'";
return $escaped;
}
// detect imagemagick type and cache response (because it might be used in files loop)
private static $imagemagick;
public static function imagemagick(){
if(isset(self::$imagemagick)) return self::$imagemagick;
// PHP imagick extension if preferred and available
if(U::prefer_imagick()) return self::$imagemagick = 'imagick';
// imagemagick is available from command-line
if(U::app_path('imagemagick')) return self::$imagemagick = 'imagemagick';
// not avaialble
return self::$imagemagick = false;
}
// prefer PHP imagick extension if available https://www.php.net/manual/en/intro.imagick.php, otherwise default to ImageMagick CLI
public static function prefer_imagick(){
return Config::get('imagemagick_prefer_imagick') && extension_loaded('imagick');
}
// 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));
if(isset($_SERVER['HTTP_RANGE'])) return self::http_range($path, $mime, $message); // support HTTP_RANGE partial content requests
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;
}
// readfile() support HTTP_RANGE requests (large video, pdf etc) when files are served through PHP
private static function http_range($path, $mime, $message){
// parse range start end
list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
if(strpos($range, ',') !== false) U::error('Requested Range Not Satisfiable', 416);
list($start, $end) = explode('-', $range);
// vars
$filesize = filesize($path);
$offset = intval($start);
$end = $end ? intval($end) : $filesize - 1;
$length = $end - $offset + 1;
// headers
http_response_code(206); // 206 Partial Content
header("Content-Range: bytes $offset-$end/$filesize");
U::header($message, false, $mime, $length, 'inline', U::basename($path));
// open and start stream
$fp = fopen($path, 'rb');
fseek($fp, $offset);
$bufferSize = 8192;
while (!feof($fp) && ($length > 0)) {
$read = ($length > $bufferSize) ? $bufferSize : $length;
echo fread($fp, $read);
$length -= $read;
flush();
}
fclose($fp);
exit;
}
// return an array of supported PHP GD image resize types //
public static function gd_image_types(){
return array_merge(['jpeg', 'jpg', 'png', 'gif'], array_filter(['webp', 'bmp', 'avif'], function($type){
return function_exists('imagecreatefrom' . $type);
}));
}
// return an array of supported and commonly used imagemagick image types (which aren't already available in gd_image_types)
public static function imagemagick_image_types(){
return U::imagemagick() ? Config::get_array('imagemagick_image_types') : [];
}
// return an array of supported image resize types, combine gd_image_types and imagemagick_image_types
// forwarded to javascript and used to determine what types can be used for folder preview
public static function resize_image_types(){
return array_merge(U::gd_image_types(), U::imagemagick_image_types());
}
// 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.");
}
// creates a 6-cipher md5 hash from a string or array of strings / used for cache paths and cache hashes based on config options
public static function hash($data){
return substr(md5(is_array($data) ? implode(':', $data) : $data), 0, 6);
}
// create a menu hash based on relevant $config and $root / used in menu cache file name and when cleaning cache
// $paths.$options / for example $paths.$options.$mtime.json / 890b15.3ed872.1744195867.json
public static function get_menu_hash($config, $root){
// hash segment from $paths that affect menu output
$paths = [
Config::$document_root,
Config::$__dir__,
$root
];
// hash segment from $options that affect menu output
$options = [
Config::$version,
$config['cache_key'],
$config['menu_max_depth'],
$config['dirs_include'],
$config['dirs_exclude'],
$config['menu_sort'],
$config['menu_load_all']
];
// when menu_load_all enabled, we need to include further config options in menu hash
if($config['menu_load_all']) $options = array_merge($options, [
$config['files_include'],
$config['files_exclude'],
U::image_resize_cache_direct($config)
]);
// return hash $paths.$options
return U::hash($paths) . '.' . U::hash($options);
}
// get dirs hash for a specific $config and $root / used in cache file names (with md5(path) and filemtime) and to determine valid cache
// all options here may dirs json output, so must be included in the hash
public static function get_dirs_hash($config, $root){
return U::hash([
Config::$document_root,
Config::$__dir__,
$root,
Config::$version,
U::image_resize_cache_direct($config),
$config['cache_key'],
$config['files_include'],
$config['files_exclude'],
$config['dirs_include'],
$config['dirs_exclude']
]);
}
// get current dirs hash and cache it (available for new Dir() loop operations)
private static $current_dirs_hash;
public static function get_current_dirs_hash(){
if(self::$current_dirs_hash) return self::$current_dirs_hash;
return self::$current_dirs_hash = self::get_dirs_hash(Config::$config, Config::$root);
}
// check if image_resize_cache_direct is enabled for a specific $config alongside required settings
public static function image_resize_cache_direct($config){
return $config['image_resize_cache_direct'] && $config['load_images'] && $config['image_resize_cache'] && $config['image_resize_enabled'];
}
// 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>
<html class="<?php echo $class; ?>" data-theme="contrast">
<script>
// fail-safe localStorage helper function
function storage(item, val) {
try {
return val ? localStorage.setItem(item, val) : localStorage.getItem(item);
} catch (e) {
return false;
};
}
// get theme from localStorage or system default
let theme = storage('files:theme') || (matchMedia('(prefers-color-scheme:dark)').matches ? 'dark' : 'contrast');
// if theme is not 'contrast' (default theme) then must data-theme in <html>
if(theme !== 'contrast') document.documentElement.dataset.theme = theme;
</script>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-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>
<link href="<?php echo U::assetspath(); ?>smooth-files-gallery@<?php echo Config::$version ?>/css/files.css" rel="stylesheet">
<?php // various custom includes
U::uinclude('include/head.html');
U::uinclude('css/custom.css');
if(Login::$is_logged_in && !Login::$is_default_user) U::uinclude('users/' . Config::get('username') . '/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/
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 = Login::$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){