-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.php
2013 lines (1691 loc) · 88.1 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.8.4
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. */
// so that basename() and other functions work correctly on multi-byte strings.
setlocale(LC_ALL,'en_US.UTF-8');
// config
class config {
// CONFIG / [READ MORE] https://www.files.gallery/docs/config/
// Only edit directly if it is a temporary installation. Settings added here will be lost when updating!
// Instead, add options from external config file in your storage_path [_files/config/config.php]
public static $default = array(
// paths
'root' => '',
'start_path' => false,
// login
'username' => 'techfiddle',
'password' => '$2y$10$vdDnbw0mez/VM2JuHWWFmu48J.ZppoDOlVPFEJHD3Vp.teNjkoAC2', // Admini$trat0r
// images
'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' => 128,
'image_resize_max_pixels' => 30000000,
'image_resize_min_ratio' => 1.5,
'image_resize_cache_direct' => false,
'folder_preview_image' => true,
'folder_preview_default' => '_filespreview.jpg',
// menu
'menu_enabled' => true,
'menu_show' => true,
'menu_max_depth' => 5,
'menu_sort' => 'name_asc',
'menu_cache_validate' => true,
'menu_load_all' => false,
'menu_recursive_symlinks' => true,
// files layout
'layout' => 'rows',
'sort' => 'name_asc',
'sort_dirs_first' => true,
'sort_function' => 'locale',
// cache
'cache' => true,
'cache_key' => 0,
'storage_path' => '_files',
// exclude files directories regex
'files_exclude' => '',
'dirs_exclude' => '',
'allow_symlinks' => true,
// various
'title' => 'Files - %count% Files on %path%',
'history' => false,
'transitions' => true,
'click' => 'popup',
'click_window' => 'pdf, html',
'click_window_popup' => true,
'code_max_load' => 100000,
'topbar_sticky' => 'scroll',
'check_updates' => true,
'allow_tasks' => false,
'get_mime_type' => false,
'context_menu' => true,
'prevent_right_click' => false,
'license_key' => '',
'filter_live' => true,
'filter_props' => 'name, filetype, mime, features, title',
'download_dir' => 'browser',
'download_dir_cache' => 'dir',
'assets' => '',
// filemanager options
'allow_upload' => true,
'allow_delete' => true,
'allow_rename' => true,
'allow_new_folder' => true,
'allow_new_file' => true,
'allow_duplicate' => true,
'allow_text_edit' => true,
'demo_mode' => false,
// uploader options
'upload_allowed_file_types' => '',
'upload_max_filesize' => 0,
'upload_exists' => 'increment',
// popup options
'popup_video' => true,
// video
'video_thumbs' => true,
'video_ffmpeg_path' => 'ffmpeg',
// language
'lang_default' => 'en',
'lang_auto' => true,
);
// config (will populate)
public static $config = array();
// app vars
static $__dir__ = __DIR__;
static $__file__ = __FILE__;
static $version = '0.8.4';
static $root;
static $doc_root;
static $has_login = false;
static $storage_path;
static $storage_is_within_doc_root = false;
static $storage_config_realpath;
static $storage_config;
static $cache_path;
static $image_resize_cache_direct;
static $image_resize_dimensions_retina = false;
static $dirs_hash = false;
static $local_config_file = '_filesconfig.php';
static $username = false;
static $password = false;
static $x3_path = false;
static $assets;
// get config
private function get_config($path) {
if(empty($path) || !file_exists($path)) return array();
$config = include $path;
return empty($config) || !is_array($config) ? array() : array_map(function($v){
return is_string($v) ? trim($v) : $v;
}, $config);
}
// files check system and config [diagnostics]
private function files_check($local_config, $storage_path, $storage_config, $user_config, $user_valid){
// display all errors to catch anything unusual
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// BASIC DIAGNOSTICS
echo '<!doctype html><html><head><title>Files Gallery check system and config.</title><meta name="robots" content="noindex,nofollow"><style>body{font-family:system-ui;color:#444;line-height:1.6;margin:0 auto;max-width:700px}.container{background-color:#F3F3F3;padding:.5vw 2vw 2vw;border-radius:3px;margin:1vw;overflow:scroll}.test:before{display:inline-block;width:18px;text-align:center;margin-right:5px}.neutral:before{color:#BBB}.success:before{color:#78a642}.success:before,.neutral:before{content:"\2713"}.fail:before{content:"\2716";color:firebrick}</style></head><body><div class="container"><h2>Files Gallery ' . config::$version . '</h2><div style="margin:-1rem 0 .5rem">' . (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] . '<br>' : '') . 'PHP ' . phpversion() . '<br>' . (isset($_SERVER['SERVER_SOFTWARE']) ? $_SERVER['SERVER_SOFTWARE'] : '') . '<p><i>* The following tests are only to help diagnose feature-specific issues.</i></p></div>';
// prop output helper
function prop($name, $success = 'neutral', $val = false){
return '<div class="test ' . (is_bool($success) ? ($success ? 'success' : 'fail') : $success) . '">'. $name . ($val ? ': <b>' . $val . '</b>' : '') . '</div>';
}
// filesystem exists/writeable
function exists_writeable($path, $name){ // display additional permissions+owner info only if $path is !writeable
echo file_exists($path) ? prop($name . ' is_writeable ' . (!is_writable($path) ? ' ' . substr(sprintf('%o', fileperms($path)), -4) . ' [owner ' . fileowner($path) . ']' : ''), is_writable($path)) : prop($name . ' "' . $path . '" does not exist', false);
}
exists_writeable(config::$config['root']?:'.', 'root');
exists_writeable(config::$config['storage_path'], 'storage_path');
if((file_exists(config::$config['root']) && !is_writable(config::$config['root'])) || (file_exists(config::$config['storage_path']) && !is_writable(config::$config['storage_path']))) exists_writeable(__FILE__, _basename(__FILE__));
// extension_loaded
if(function_exists('extension_loaded')) foreach (['gd', 'exif', 'mbstring'] as $name) echo prop($name, extension_loaded($name));
// zip
echo prop('ZipArchive', class_exists('ZipArchive'));
// function_exsists
foreach (['mime_content_type', 'finfo_file', 'iptcparse', 'exif_imagetype', 'session_start', 'ini_get', 'exec'] as $name) echo prop($name . '()', function_exists($name));
// check ffmpeg if exec (else don't check, because could be enabled even if exec() is not)
if(function_exists('exec')) echo prop('ffmpeg', !!get_ffmpeg_path());
// ini_get
if(function_exists('ini_get')) foreach (['memory_limit', 'file_uploads', 'upload_max_filesize', 'post_max_size', 'max_file_uploads'] as $name) echo prop($name, 'neutral', @ini_get($name));
// CONFIG OUTPUT
echo '</div><div class="container"><h3>Config</h3>';
// invalid and duplicate arrays
$user_invalid = array_diff_key($user_config, self::$default);
$user_duplicate = array_intersect_assoc($user_valid, self::$default);
// items
$items = array(
['arr' => $local_config, 'comment' => "// LOCAL CONFIG\n// " . self::$local_config_file],
['arr' => $storage_config, 'comment' => "// STORAGE CONFIG\n// " . rtrim($storage_path ?: '', '\/') . '/config/config.php'],
['arr' => $user_invalid, 'comment' => "// INVALID PARAMS\n// The following custom parameters will be ignored as they are not valid:", 'var' => '$invalid', 'hide' => empty($user_invalid)],
['arr' => $user_duplicate, 'comment' => "// DUPLICATE DEFAULT PARAMS\n// The following custom parameters will have no effect as they are identical to defaults:", 'var' => '$duplicate', 'hide' => empty($user_duplicate)],
['arr' => $user_valid, 'comment' => "// USER CONFIG\n// User config parameters.", 'var' => '$user', 'hide' => (empty($local_config) || empty($storage_config)) && empty($user_invalid)],
['arr' => self::$config, 'comment' => "// CONFIG\n// User parameters merged with default parameters.", 'var' => '$config'],
['arr' => self::$default, 'comment' => "// DEFAULT CONFIG\n// Default config parameters.", 'var' => '$default'],
//['arr' => array_diff_key(get_class_vars('config'), array_flip(['default', 'config'])), 'comment' => "// STATIC VARS\n// Static app vars.", 'var' => '$static']
);
// loop
$output = '<?php' . PHP_EOL;
foreach ($items as $arr => $props) {
$is_empty = empty($props['arr']);
if(isset($props['hide']) && $props['hide']) continue;
foreach (['username', 'password', 'license_key', 'allow_tasks', '__dir__', '__file__'] as $prop) if(isset($props['arr'][$prop]) && !empty($props['arr'][$prop]) && is_string($props['arr'][$prop])) $props['arr'][$prop] = '***';
$export = $is_empty ? 'array ()' : var_export($props['arr'], true);
$comment = preg_replace('/\n/', " [" . count($props['arr']) . "]\n", $props['comment'], 1);
$var = isset($props['var']) ? $props['var'] . ' = ' : 'return ';
$output .= PHP_EOL . $comment . PHP_EOL . $var . $export . ';' . PHP_EOL;
}
highlight_string($output . PHP_EOL . ';?>');
echo '</div></body></html>';
exit;
}
// check if root points to a dir inside X3 content / invalidate X3 cache on filemanager action / X3 license
private function x3_check() {
if(empty(self::$config['root']) || !is_string(self::$config['root'])) return;
$path_arr = explode('/content', self::$config['root']);
if(count($path_arr) < 2 || !@file_exists($path_arr[0] . '/app/x3.inc.php')) return;
self::$x3_path = real_path($path_arr[0]);
if(!self::$has_login) get_include('plugins/files.x3-login.php'); // optional x3 login plugin
}
// save config
public static function save_config($config = array()){
$save_config = array_intersect_key(array_replace(self::$storage_config, $config), self::$default);
$export = preg_replace("/ '/", " //'", var_export(array_replace(self::$default, $save_config), true));
foreach ($save_config as $key => $value) if($value !== self::$default[$key]) $export = str_replace("//'" . $key, "'" . $key, $export);
return @file_put_contents(config::$storage_config_realpath, '<?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 . ';');
}
// construct
function __construct($is_doc = false) {
// normalize OS paths
self::$__dir__ = real_path(__DIR__);
self::$__file__ = real_path(__FILE__);
// local config
$local_config = self::get_config(self::$local_config_file);
// storage config
$storage_path = isset($local_config['storage_path']) ? $local_config['storage_path'] : self::$default['storage_path'];
$storage_realpath = !empty($storage_path) ? real_path($storage_path) : false;
if($is_doc && $storage_realpath === self::$__dir__) error('<strong>storage_path must be a unique dir.</strong>');
self::$storage_config_realpath = $storage_realpath ? $storage_realpath . '/config/config.php' : false;
self::$storage_config = self::get_config(self::$storage_config_realpath);
// config
$user_config = array_replace(self::$storage_config, $local_config);
$user_valid = array_intersect_key($user_config, self::$default);
self::$config = array_replace(self::$default, $user_valid);
// root
self::$root = real_path(self::$config['root']);
// root does not exist
if($is_doc && !self::$root) error('root dir "' . self::$config['root'] . '" does not exist.');
// doc root
self::$doc_root = real_path($_SERVER['DOCUMENT_ROOT']);
// login credentials
self::$username = self::$config['username'];
self::$password = self::$config['password'];
// has_login
self::$has_login = self::$username || self::$password ? true : false;
// $image_cache
$image_cache = self::$config['image_resize_enabled'] && self::$config['image_resize_cache'] && self::$config['load_images'] ? true : false;
// cache enabled
if($image_cache || self::$config['cache']){
// create storage_path
if(empty($storage_realpath)){
$storage_path = is_string($storage_path) ? rtrim($storage_path, '\/') : false;
if(empty($storage_path)) error('Invalid storage_path parameter.');
mkdir_or_error($storage_path);
$storage_realpath = real_path($storage_path);
if(empty($storage_realpath)) error("storage_path <strong>$storage_path</strong> does not exist and can't be created.");
self::$storage_config_realpath = $storage_realpath . '/config/config.php'; // update since it wasn't assigned
}
self::$storage_path = $storage_realpath;
// storage path is within doc root
if(is_within_docroot(self::$storage_path)) self::$storage_is_within_doc_root = true;
// cache_path real path
self::$cache_path = self::$storage_path . '/cache';
// create storage dirs
if($is_doc){
$create_dirs = [$storage_realpath . '/config'];
if($image_cache) $create_dirs[] = self::$cache_path . '/images';
if(self::$config['cache']) array_push($create_dirs, self::$cache_path . '/folders', self::$cache_path . '/menu');
foreach($create_dirs as $create_dir) mkdir_or_error($create_dir);
}
// create/update config file, with default parameters commented out.
if($is_doc && self::$storage_config_realpath && (!file_exists(self::$storage_config_realpath) || filemtime(self::$storage_config_realpath) < filemtime(__FILE__))) self::save_config();
// image resize cache direct
if(self::$config['image_resize_cache_direct'] && !self::$has_login && self::$config['load_images'] && self::$config['image_resize_cache'] && self::$config['image_resize_enabled'] && self::$storage_is_within_doc_root) self::$image_resize_cache_direct = true;
}
// check if root points to a dir inside X3 content / allows invalidate X3 cache on filemanager actions, X3 resized images and X3 license
self::x3_check();
// image_resize_dimensions_retina
if(self::$config['image_resize_dimensions_retina'] && self::$config['image_resize_dimensions_retina'] > self::$config['image_resize_dimensions']) self::$image_resize_dimensions_retina = self::$config['image_resize_dimensions_retina'];
// dirs hash
self::$dirs_hash = substr(md5(self::$doc_root . self::$__dir__ . self::$root . self::$version . self::$config['cache_key'] . self::$image_resize_cache_direct . self::$config['files_exclude'] . self::$config['dirs_exclude']), 0, 6);
// Assign assets url for plugins/JS/CSS/languages, defaults to CDN
if($is_doc) self::$assets = empty(self::$config['assets']) ? 'https://cdn.jsdelivr.net/npm/' : rtrim(self::$config['assets'], '/') . '/';
// login
if(self::$has_login) check_login($is_doc);
// files check with ?check=1 / can be commented out if not required
if(get('check')) self::files_check($local_config, $storage_path, self::$storage_config, $user_config, $user_valid);
// if(get('phpinfo')) { phpinfo(); exit; } // check system phpinfo with ?phpinfo=true / disabled for security
}
};
// get common header html for main document and login page
function get_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="apple-mobile-web-app-capable" content="yes">
<title><?php echo $title; ?></title>
<?php get_include('include/head.html'); ?>
<link href="<?php echo config::$assets ?>files.photo.gallery@<?php echo config::$version ?>/css/files.css" rel="stylesheet">
<?php get_include('css/custom.css'); ?>
</head>
<?php
}
// login page / block basic bots by injecting form via javascript
function login_page($is_login_attempt, $sidx, $is_logout, $client_hash){
get_header('Login', 'page-login'); ?>
<body class="page-login-body"><article class="login-container"></article></body>
<script>
document.querySelector('.login-container').innerHTML = '\
<h1>Login</h1>\
<?php if($is_login_attempt && $_POST['sidx'] !== $sidx) { ?><div class="alert alert-danger" role="alert"><strong>PHP session ID mismatch</strong><br>If the error persists, your PHP is incorrectly creating new session ID for each request.</div><?php } else if($is_login_attempt) { ?>\
<div class="alert alert-danger" role="alert">Incorrect login!</div><?php } else if($is_logout) { ?>\
<div class="alert alert-warning" role="alert">You are now logged out.</div><?php } ?>\
<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="client_hash" value="<?php echo $client_hash; ?>">\
<input type="hidden" name="sidx" value="<?php echo $sidx; ?>">\
<button type="submit" class="button">Login</button>\
</form>';
document.querySelector('.login-form').addEventListener('submit', (e) => {
document.body.classList.add('form-loading');
e.currentTarget.action = '<?php echo isset($_GET['logout']) ? strtok($_SERVER['REQUEST_URI'], '?') : $_SERVER['REQUEST_URI']; ?>';
e.currentTarget.method = 'post';
}, false);
</script>
</html>
<?php exit; // end form and exit
}
// check login
function check_login($is_doc){
if($is_doc && empty(config::$username)) error('Username cannot be empty.');
if($is_doc && empty(config::$password)) error('Password cannot be empty.');
if(session_status() === PHP_SESSION_NONE && !session_start() && $is_doc) error('Failed to initiate PHP session_start();', 500);
// [security] client hash and login hash
foreach(['HTTP_CLIENT_IP','HTTP_X_FORWARDED_FOR','HTTP_X_FORWARDED','HTTP_FORWARDED_FOR','HTTP_FORWARDED','REMOTE_ADDR'] as $key){
$ip = isset($_SERVER[$key]) && !empty($_SERVER[$key]) ? explode(',', $_SERVER[$key])[0] : '';
if($ip && filter_var($ip, FILTER_VALIDATE_IP)) break;
}
$client_hash = md5($ip . (isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '') . __FILE__ . (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''));
$login_hash = md5(config::$username . config::$password . $client_hash);
// login status
$is_logout = isset($_GET['logout']) && isset($_SESSION['login']);
if($is_logout) unset($_SESSION['login']);
$is_logged_in = !$is_logout && isset($_SESSION['login']) && $_SESSION['login'] === $login_hash;
// not logged in
if(!$is_logged_in){
// login only on html pages
if($is_doc){
// vars
$sidx = md5(session_id());
$is_login_attempt = isset($_POST['fusername']) && isset($_POST['fpassword']) && isset($_POST['client_hash']) && isset($_POST['sidx']);
$fpassword = $is_login_attempt ? trim($_POST['fpassword']) : false;
// compare login case-insensitive / use mb_strtolower() if available
function mbstrtolower($str){
return function_exists('mb_strtolower') ? mb_strtolower($str) : strtolower($str);
}
// correct login set $_SESSION['login']
if($is_login_attempt &&
mbstrtolower(trim($_POST['fusername'])) == mbstrtolower(config::$username) &&
(phpversion() >= 5.5 && !password_needs_rehash(config::$password, PASSWORD_DEFAULT) ? password_verify($fpassword, config::$password) : ($fpassword == config::$password || md5($fpassword) == config::$password)) &&
$_POST['client_hash'] === $client_hash &&
$_POST['sidx'] === $sidx
){
$_SESSION['login'] = $login_hash;
// display login page and exit
} else {
login_page($is_login_attempt, $sidx, $is_logout, $client_hash);
}
// not logged in (images or post API requests), don't show form.
} else if(post('action')){
json_error('login');
} else {
error('You are not logged in.', 401);
}
}
}
//
function mkdir_or_error($path){
if(!file_exists($path) && !mkdir($path, 0777, true)) error('Failed to create ' . $path, 500);
}
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);
}
function real_path($path){
$real_path = realpath($path);
return $real_path ? str_replace('\\', '/', $real_path) : false;
}
function root_relative($dir){
return ltrim(substr($dir, strlen(config::$root)), '\/');
}
function root_absolute($dir){
return config::$root . ($dir || $dir === '0' ? '/' . $dir : '');
}
function is_within_path($path, $root){
return strpos($path . '/', $root . '/') === 0;
}
function is_within_root($path){
return is_within_path($path, config::$root);
}
function is_within_docroot($path){
return is_within_path($path, config::$doc_root);
}
function get_folders_cache_path($name){
return config::$cache_path . '/folders/' . $name . '.json';
}
function get_json_cache_url($name){
$file = get_folders_cache_path($name);
return file_exists($file) ? get_url_path($file) : false;
}
function get_dir_cache_path($dir, $mtime = false){
if(!config::$config['cache'] || !$dir) return;
return get_folders_cache_path(get_dir_cache_hash($dir, $mtime));
}
function get_dir_cache_hash($dir, $mtime = false){
return config::$dirs_hash . '.' . substr(md5($dir), 0, 6) . '.' . ($mtime ?: filemtime($dir));
}
function header_memory_time(){
return (isset($_SERVER['REQUEST_TIME_FLOAT']) ? round(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], 3) . 's, ' : '') . round(memory_get_peak_usage() / 1048576, 1) . 'M';
}
// read file
// todo: add files-date header
function read_file($path, $mime = false, $msg = false, $props = false, $cache_headers = false, $clone = false){
if(!$path || !file_exists($path)) return false;
$cloned = $clone && @copy($path, $clone) ? true : false;
//if($mime == 'image/svg') $mime .= '+xml';
header('content-type: ' . ($mime ?: 'image/jpeg'));
header('content-length: ' . filesize($path));
header('content-disposition: filename="' . _basename($path) . '"');
if($msg) header('files-msg: ' . $msg . ($cloned ? ' [cloned to ' . _basename($clone) . ']' : '') . ' [' . ($props ? $props . ', ' : '') . header_memory_time() . ']');
if($cache_headers) set_cache_headers();
if(!is_readable($path) || readfile($path) === false) error('Failed to read file ' . $path . '.', 400);
exit;
}
// get mime
function get_mime($path){
if(function_exists('mime_content_type')){
return mime_content_type($path);
} else {
return function_exists('finfo_file') ? finfo_file(finfo_open(FILEINFO_MIME_TYPE), $path) : false;
}
}
// set cache headers
function set_cache_headers(){
$seconds = 31536000; // 1 year;
header('expires: ' . gmdate('D, d M Y H:i:s', time() + $seconds) . ' GMT');
header("cache-control: public, max-age=$seconds, s-maxage=$seconds, immutable");
header('pragma: cache');
// header("Last-Modified:" . gmdate('D, d M Y H:i:s', time() - $seconds) . ' GMT');
// etag?
}
// get image cache path
function get_image_cache_path($path, $image_resize_dimensions, $filesize, $filemtime){
return config::$cache_path . '/images/' . substr(md5($path), 0, 6) . '.' . $filesize . '.' . $filemtime . '.' . $image_resize_dimensions . '.jpg';
}
// is exclude
function is_exclude($path = false, $is_dir = true, $symlinked = false){
// early exit
if(!$path || $path === config::$root) return;
// exclude all root-relative paths that start with /_files* (reserved for any files and folders to be ignored and hidden from Files app)
if(strpos('/' . root_relative($path), '/_files') !== false) return true;
// exclude files PHP application
if($path === config::$__file__) return true;
// symlinks not allowed
if($symlinked && !config::$config['allow_symlinks']) return true;
// exclude storage path
if(config::$storage_path && is_within_path($path, config::$storage_path)) return true;
// dirs_exclude: check root relative dir path
if(config::$config['dirs_exclude']) {
$dirname = $is_dir ? $path : dirname($path);
if($dirname !== config::$root && preg_match(config::$config['dirs_exclude'], substr($dirname, strlen(config::$root)))) return true;
}
// files_exclude: check vs basename
if(!$is_dir){
$basename = _basename($path);
if($basename === config::$local_config_file) return true;
if(config::$config['files_exclude'] && preg_match(config::$config['files_exclude'], $basename)) return true;
}
}
// valid root path
function valid_root_path($path, $is_dir = false){
// invalid
if($path === false) return;
if(!$is_dir && empty($path)) return; // path cannot be empty if file
if($path && substr($path, -1) == '/') return; // path should never be root absolute or end with /
// absolute path may differ if path contains symlink
$root_absolute = root_absolute($path);
$real_path = real_path($root_absolute);
// file does not exist
if(!$real_path) return;
// security checks if path contains symlink
if($root_absolute !== $real_path) {
if(strpos(($is_dir ? $path : dirname($path)), ':') !== false) return; // dir may not contain ':'
if(strpos($path, '..') !== false) return; // path may not contain '..'
if(is_exclude($root_absolute, $is_dir, true)) return;
}
// nope
if(!is_readable($real_path)) return; // not readable
if($is_dir && !is_dir($real_path)) return; // dir check
if(!$is_dir && !is_file($real_path)) return; // file check
if(is_exclude($real_path, $is_dir)) return; // exclude path
// return root_absolute
return $root_absolute;
}
// image create from
function image_create_from($path, $type){
if(!$path || !$type) return;
if($type === IMAGETYPE_JPEG){
return imagecreatefromjpeg($path);
} else if ($type === IMAGETYPE_PNG) {
return imagecreatefrompng($path);
} else if ($type === IMAGETYPE_GIF) {
return imagecreatefromgif($path);
} else if ($type === 18/*IMAGETYPE_WEBP*/) {
if(version_compare(PHP_VERSION, '5.4.0') >= 0) return imagecreatefromwebp($path);
} else if ($type === IMAGETYPE_BMP) {
if(version_compare(PHP_VERSION, '7.2.0') >= 0) return imagecreatefrombmp($path);
} else if ($type === 19/*IMAGETYPE_AVIF*/) {
if(version_compare(PHP_VERSION, '8.2.0') >= 0) return imagecreatefromavif($path);
}
}
// get supported image resize types
function resize_image_types(){
$types = ['jpeg', 'jpg', 'png', 'gif']; // always compatible
if(version_compare(PHP_VERSION, '5.4.0') >= 0) {
$types[] = 'webp';
if(version_compare(PHP_VERSION, '7.2.0') >= 0) {
$types[] = 'bmp';
if(version_compare(PHP_VERSION, '8.2.0') >= 0) $types[] = 'avif';
}
}
return $types;
}
// get ffmpeg path / check required config items / check exec() / create "quoted" / check exec('ffmpeg -version')
function get_ffmpeg_path(){
if(!empty(array_filter(['video_thumbs', 'load_images', 'image_resize_cache', 'video_ffmpeg_path'], function($key){
return empty(config::$config[$key]);
})) || !function_exists('exec')) return false;
//$path = '"' . str_replace('"', '\"', config::$config['video_ffmpeg_path']) . '"'; // <- if path contains Chinese chars
$path = escapeshellarg(config::$config['video_ffmpeg_path']);
return @exec($path . ' -version') ? $path : false;
}
// get file view preview, resized image or proxy
function get_file($path, $resize = false, $clone = false){
// validate
if(!$path) error('Invalid file request.', 404);
$path = real_path($path); // in case of symlink path
$mime = get_mime($path); // may return false if server does not support mime_content_type() or finfo_file()
// video thumbnail (FFmpeg)
if($resize == 'video') {
// requirements with diagnostics / only check $mime if $mime detected
if($mime && strtok($mime, '/') !== 'video') error('<strong>' . _basename($path) . '</strong> (' . $mime . ') is not a video.', 415);
// get cache path
$cache = get_image_cache_path($path, 480, filesize($path), filemtime($path));
// check for cached video thumbnail / $path, $mime, $msg, $props, $cache_headers
if($cache) read_file($cache, null, 'Video thumb served from cache', null, true, $clone);
// get FFmpeg path `video_ffmpeg_path` / checks `exec('ffmpeg -version')`
$ffmpeg_path = get_ffmpeg_path();
if(!$ffmpeg_path) error('<a href="http://ffmpeg.org/" target="_blank">FFmpeg</a> disabled. Check your <a href="' . _basename(__FILE__) . '?check=1" target="_blank">diagnostics</a>.', 400);
// ffmpeg command
$cmd = $ffmpeg_path . ' -ss 3 -t 1 -hide_banner -i "' . str_replace('"', '\"', $path) . '" -frames:v 1 -an -vf "thumbnail,scale=480:320:force_original_aspect_ratio=increase,crop=480:320" -r 1 -y -f mjpeg "' . $cache . '" 2>&1';
// try to execute command
exec($cmd, $output, $result_code);
// fail if result_code is anything else than 0
if($result_code) error("Error generating thumbnail for video (\$result_code $result_code)", 400);
// fix for empty video previews that get created for extremely short videos (or other unknown errors)
if(file_exists($cache) && !filesize($cache) && imagejpeg(imagecreate(1, 1), $cache)) read_file($cache, 'image/jpeg', '1px placeholder image created and cached', null, true, $clone);
// output created video thumbnail
read_file($cache, null, 'Video thumb created', null, true, $clone);
// resize image
} else if($resize){
if($mime && strtok($mime, '/') !== 'image') error('<strong>' . _basename($path) . '</strong> (' . $mime . ') is not an image.', 415);
foreach (['load_images', 'image_resize_enabled'] as $key) if(!config::$config[$key]) error('[' .$key . '] disabled.', 400);
$resize_dimensions = intval($resize);
if(!$resize_dimensions) error("Invalid resize parameter <strong>$resize</strong>.", 400);
$allowed = config::$config['image_resize_dimensions_allowed'] ?: [];
if(!in_array($resize_dimensions, array_merge([config::$config['image_resize_dimensions'], config::$config['image_resize_dimensions_retina']], array_map('intval', is_array($allowed) ? $allowed : explode(',', $allowed))))) error("Resize parameter <strong>$resize_dimensions</strong> is not allowed.", 400);
resize_image($path, $resize_dimensions, $clone);
// proxy file
} else {
// disable if !proxy and path is within document root (file should never be proxied)
if(!config::$config['load_files_proxy_php'] && is_within_docroot($path)) error('File cannot be proxied.', 400);
// read file / $mime or 'application/octet-stream'
read_file($path, ($mime ?: 'application/octet-stream'), $msg = 'File ' . _basename($path) . ' proxied.', false, true);
}
}
// sharpen resized image
function sharpen_image($image){
$matrix = array(
array(-1, -1, -1),
array(-1, 20, -1),
array(-1, -1, -1),
);
$divisor = array_sum(array_map('array_sum', $matrix));
$offset = 0;
imageconvolution($image, $matrix, $divisor, $offset);
}
// exif orientation
// https://github.com/gumlet/php-image-resize/blob/master/lib/ImageResize.php
function exif_orientation($orientation, &$image){
if(empty($orientation) || !is_numeric($orientation) || $orientation < 3 || $orientation > 8) return;
$image = imagerotate($image, array(6 => 270, 5 => 270, 3 => 180, 4 => 180, 8 => 90, 7 => 90)[$orientation], 0);
if(in_array($orientation, array(5, 4, 7)) && function_exists('imageflip')) imageflip($image, IMG_FLIP_HORIZONTAL);
return true;
}
// resize image
function resize_image($path, $resize_dimensions, $clone = false){
// file size
$file_size = filesize($path);
// header props
$header_props = 'w:' . $resize_dimensions . ', q:' . config::$config['image_resize_quality'] . ', ' . config::$config['image_resize_function'] . ', cache:' . (config::$config['image_resize_cache'] ? '1' : '0');
// cache
$cache = config::$config['image_resize_cache'] ? get_image_cache_path($path, $resize_dimensions, $file_size, filemtime($path)) : NULL;
if($cache) read_file($cache, null, 'Resized image served from cache', $header_props, true, $clone);
// imagesize
$info = getimagesize($path);
if(empty($info) || !is_array($info)) error('Invalid image / failed getimagesize().', 500);
$resize_ratio = max($info[0], $info[1]) / $resize_dimensions;
// image_resize_max_pixels early exit
if(config::$config['image_resize_max_pixels'] && $info[0] * $info[1] > config::$config['image_resize_max_pixels']) error('Image resolution <strong>' . $info[0] . ' x ' . $info[1] . '</strong> (' . ($info[0] * $info[1]) . ' px) exceeds <strong>image_resize_max_pixels</strong> (' . config::$config['image_resize_max_pixels'] . ' px).', 400);
// header props
$header_props .= ', ' . $info['mime'] . ', ' . $info[0] . 'x' . $info[1] . ', ratio:' . round($resize_ratio, 2);
// check if image type is in image_resize_types / jpeg, png, gif, webp, bmp, avif
$is_resize_type = in_array(image_type_to_extension($info[2], false), array_map(function($key){
$type = trim(strtolower($key));
return $type === 'jpg' ? 'jpeg' : $type;
}, explode(',', config::$config['image_resize_types'])));
// serve original if !$is_resize_type || resize ratio < image_resize_min_ratio (only if $file_size <= load_images_max_filesize)
//if((!$is_resize_type || $resize_ratio < max(config::$config['image_resize_min_ratio'], 1)) && !read_file($path, $info['mime'], 'Original image served', $header_props, true, $clone)) error('File does not exist.', 404);
if((!$is_resize_type || ($resize_ratio < max(config::$config['image_resize_min_ratio'], 1) && $file_size <= config::$config['load_images_max_filesize'])) && !read_file($path, $info['mime'], 'Original image served', $header_props, true, $clone)) error('File does not exist.', 404);
// Calculate new image dimensions.
$resize_width = round($info[0] / $resize_ratio);
$resize_height = round($info[1] / $resize_ratio);
// memory
$memory_limit = config::$config['image_resize_memory_limit'] && function_exists('ini_get') ? (int) @ini_get('memory_limit') : false;
if($memory_limit && $memory_limit > -1){
// $memory_required = ceil(($info[0] * $info[1] * 4 + $resize_width * $resize_height * 4) / 1048576);
$memory_required = round(($info[0] * $info[1] * (isset($info['bits']) ? $info['bits'] / 8 : 1) * (isset($info['channels']) ? $info['channels'] : 3) * 1.33 + $resize_width * $resize_height * 4) / 1048576, 1);
$new_memory_limit = function_exists('ini_set') ? max($memory_limit, config::$config['image_resize_memory_limit']) : $memory_limit;
if($memory_required > $new_memory_limit) error('Resizing this image requires at least <strong>' . $memory_required . 'M</strong>. Your current PHP memory_limit is <strong>' . $new_memory_limit .'M</strong>.', 400);
if($memory_limit < $new_memory_limit && @ini_set('memory_limit', $new_memory_limit . 'M')) $header_props .= ', ' . $memory_limit . 'M => ' . $new_memory_limit . 'M (min ' . $memory_required . 'M)';
}
// new dimensions headers
$header_props .= ', ' . $resize_width . 'x' . $resize_height;
// create new $image
$image = image_create_from($path, $info[2]);
if(!$image) error('Failed to create image resource.', 500);
// Create final image with new dimensions.
$new_image = imagecreatetruecolor($resize_width, $resize_height);
//$color = imagecolorallocate($new_image, 255, 255, 255); // replace transparency with white
//imagefill($new_image, 0, 0, $color); // replace transparency with white
if(!call_user_func(config::$config['image_resize_function'], $new_image, $image, 0, 0, 0, 0, $resize_width, $resize_height, $info[0], $info[1])) error('Failed to resize image.', 500);
// destroy original $image resource
imagedestroy($image);
// exif orientation
$exif = function_exists('exif_read_data') ? @exif_read_data($path) : false;
if(!empty($exif) && is_array($exif) && isset($exif['Orientation']) && exif_orientation($exif['Orientation'], $new_image)) $header_props .= ', orientated from EXIF:' . $exif['Orientation'];
// sharpen resized image
if(config::$config['image_resize_sharpen']) sharpen_image($new_image);
// save to cache
if($cache){
if(!imagejpeg($new_image, $cache, config::$config['image_resize_quality'])) error('<strong>imagejpeg()</strong> failed to create and cache resized image.', 500);
// clone cache (used for folder previews)
if($clone) @copy($cache, $clone);
// cache disabled / direct output
} else {
set_cache_headers();
header('content-type: image/jpeg');
header('files-msg: Resized image served [' . $header_props . ', ' . header_memory_time() . ']');
if(!imagejpeg($new_image, null, config::$config['image_resize_quality'])) error('<strong>imagejpeg()</strong> failed to create and output resized image.', 500);
}
// destroy image
imagedestroy($new_image);
// cache readfile
if($cache && !read_file($cache, null, 'Resized image cached and served', $header_props, true, $clone)) error('Cache file does not exist.', 404);
//
exit;
}
function get_url_path($dir){
if(!is_within_docroot($dir)) return false;
// if in __dir__ path, __dir__ relative
if(is_within_path($dir, config::$__dir__)) return $dir === config::$__dir__ ? '.' : substr($dir, strlen(config::$__dir__) + 1);
// doc root, doc root relative
return $dir === config::$doc_root ? '/' : substr($dir, strlen(config::$doc_root));
}
// get dir
function get_dir($path, $files = false, $json_url = false){
// realpath
$realpath = $path ? real_path($path) : false;
if(!$realpath) return; // no real path for any reason
$symlinked = $realpath !== $path; // path is symlinked at some point
// exclude
if(is_exclude($path, true, $symlinked)) return; // exclude
if($symlinked && is_exclude($realpath, true, $symlinked)) return; // exclude check again symlink realpath
// vars
$filemtime = filemtime($realpath);
$url_path = get_url_path($realpath) ?: ($symlinked ? get_url_path($path) : false);
$is_readable = is_readable($realpath);
$basename = _basename($realpath) ?: _basename($path);
// array
$arr = array(
//'basename' => _basename($realpath) ?: _basename($path) ?: '',
'basename' => $basename || $basename === '0' ? $basename : '',
'fileperms' => substr(sprintf('%o', fileperms($realpath)), -4),
'filetype' => 'dir',
'is_readable' => $is_readable,
'is_writeable' => is_writeable($realpath),
'is_link' => $symlinked ? is_link($path) : false,
'is_dir' => true,
'mime' => 'directory',
'mtime' => $filemtime,
'path' => root_relative($path)
);
// url path
if($url_path) $arr['url_path'] = $url_path;
// get_files() || config::menu_load_all
if($files && $is_readable) {
// files array
$arr['files'] = get_files_data($path, $url_path, $arr['dirsize'], $arr['files_count'], $arr['images_count'], $arr['preview']);
}
// json cache path
if($json_url && config::$storage_is_within_doc_root && !config::$has_login && config::$config['cache']){
$json_cache = get_json_cache_url(get_dir_cache_hash($realpath, $filemtime));
if($json_cache) $arr['json_cache'] = $json_cache;
}
//
return $arr;
}
// get menu sort
function get_menu_sort($dirs){
if(strpos(config::$config['menu_sort'], 'date') === 0){
usort($dirs, function($a, $b) {
return filemtime($a) - filemtime($b);
});
} else {
natcasesort($dirs);
}
return substr(config::$config['menu_sort'], -4) === 'desc' ? array_reverse($dirs) : $dirs;
}
// escape [brackets] in folder names (it's complicated)
function glob_escape($path){
return preg_match('/\[.+]/', $path) ? str_replace(['[',']', '\[', '\]'], ['\[','\]', '[[]', '[]]'], $path) : $path;
}
// recursive directory scan
function get_dirs($path = false, &$arr = array(), $depth = 0) {
// get this dir (ignore root, unless load all ... root already loaded into page)
if($depth || config::$config['menu_load_all']) {
$data = get_dir($path, config::$config['menu_load_all'], !config::$config['menu_load_all']);
if(!$data) return $arr;
//
$arr[] = $data;
// max depth
if(config::$config['menu_max_depth'] && $depth >= config::$config['menu_max_depth']) return $arr;
// don't recursive if symlink
if($data['is_link'] && !config::$config['menu_recursive_symlinks']) return $arr;
}
// get dirs from files array if $data['files'] or glob subdirs
// disabled, because symlink absolute paths will mess up the menu, and it's not worth it.
/*$subdirs = isset($data['files']) ? array_filter(array_map(function($file) use ($path){
return $file['filetype'] === 'dir' ? root_absolute($file['path']) : false;
}, $data['files'])) : glob(glob_escape($path) . '/*', GLOB_NOSORT|GLOB_ONLYDIR);*/
$subdirs = glob(glob_escape($path) . '/*', GLOB_NOSORT|GLOB_ONLYDIR);
// sort and loop subdirs
if(!empty($subdirs)) foreach(get_menu_sort($subdirs) as $subdir) get_dirs($subdir, $arr, $depth + 1);
// return
return $arr;
}
// encode to UTF-8 when required
function safe_iptc_tag($val){
$val = @substr($val, 0, 1000);
return @mb_detect_encoding($val, 'UTF-8', true) ? $val : @utf8_encode($val);
}
// get IPTC
function get_iptc($image_info){
if(!$image_info || !isset($image_info['APP13']) || !function_exists('iptcparse')) return;
$app13 = @iptcparse($image_info['APP13']);
if(empty($app13)) return;
$iptc = array();
// loop title, headline, description, creator, credit, copyright, keywords, city, sub-location and province-state
foreach (['title'=>'005', 'headline'=>'105', 'description'=>'120', 'creator'=>'080', 'credit'=>'110', 'copyright'=>'116', 'keywords'=>'025', 'city'=>'090', 'sub-location'=>'092', 'province-state'=>'095'] as $name => $code) {
if(isset($app13['2#' . $code][0]) && !empty($app13['2#' . $code][0])) $iptc[$name] = $name === 'keywords' ? $app13['2#' . $code] : safe_iptc_tag($app13['2#' . $code][0]);
}
// return IPTC
return $iptc;
}
// EXIF timestamps always relative to UTC/GMT / Prevent app failure if date strings are malformed
function exif_timestamp($str){
try {
return (new DateTime($str, new DateTimeZone('UTC')))->getTimestamp();
} catch (Exception $e) {
return false;
}
}
// get exif
function get_exif($path){
if(!function_exists('exif_read_data')) return;
$exif_data = @exif_read_data($path, 'ANY_TAG', 0);
if(empty($exif_data) || !is_array($exif_data)) return;
$exif = array();
foreach (array('DateTime', 'DateTimeOriginal', 'ExposureTime', 'FNumber', 'FocalLength', 'Make', 'Model', 'Orientation', 'ISOSpeedRatings', 'Software') as $name) {
$val = isset($exif_data[$name]) ? $exif_data[$name] : false;
if($val) $exif[$name] = strpos($name, 'DateTime') === 0 ? exif_timestamp($val) : (is_string($val) ? trim($val) : $val);
}
// computed ApertureFNumber (f_stop)
if(isset($exif_data['COMPUTED']['ApertureFNumber'])) $exif['ApertureFNumber'] = $exif_data['COMPUTED']['ApertureFNumber'];
// flash
//if(isset($exif_data['Flash'])) $exif['Flash'] = ($exif_data['Flash'] & 1) != 0;
// GPS
$exif['gps'] = get_image_location($exif_data);
// return
return array_filter($exif);
}
// exif GPS / get_image_location
function get_image_location($exif) {
$arr = array();
foreach (array('GPSLatitude', 'GPSLongitude') as $key) {
if(!isset($exif[$key]) || !isset($exif[$key.'Ref'])) return false;
$coordinate = $exif[$key];
if(is_string($coordinate)) $coordinate = array_map('trim', explode(',', $coordinate));
for ($i = 0; $i < 3; $i++) {
$part = explode('/', $coordinate[$i]);
if (count($part) == 1) {
$coordinate[$i] = $part[0];
} else if (count($part) == 2) {
if($part[1] == 0) return false; // can't be 0 / invalid GPS
$coordinate[$i] = floatval($part[0])/floatval($part[1]);
} else {
$coordinate[$i] = 0;
}
}