-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.php
2064 lines (1747 loc) · 91.6 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
// errors
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// config
class config {
// DEFAULT 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]
// READ MORE: https://forum.photo.gallery/viewtopic.php?f=66&t=9964
public static $default = array(
// paths
'root' => '', // root path relative to script / empty is same as files app location
'start_path' => false, // start path relative to script. If empty, root is start path
// login
'username' => 'aziz',
'password' => '4212', // Add password directly or use https://files.photo.gallery/tools/hash/ to encrypt the password (encrypted password is more secure, as it prevents your password from being exposed directly in a file).
// images
'load_images' => true,
'load_files_proxy_php' => false,
'load_images_max_filesize' => 1000000, // maximum file size (bytes) for un-resized images loaded into list
'load_svg_max_filesize' => 100000, // 100k
'image_resize_enabled' => true, // resize images for the interface
'image_resize_cache' => true, // todo: remove this option and just use 'cache?
'image_resize_dimensions' => 320,
'image_resize_dimensions_retina' => 480,
'image_resize_dimensions_allowed' => '', // comma-separated list of allowed resize dimensions
'image_resize_types' => 'jpeg, png, gif, webp, bmp', // image types to resize / jpeg, png, gif, webp, bmp
'image_resize_quality' => 85,
'image_resize_function' => 'imagecopyresampled', // imagecopyresampled / imagecopyresized
'image_resize_sharpen' => true,
'image_resize_memory_limit' => 128, // 128 MB is suffient to resize images around 6000 px / 0 = ignore memory
'image_resize_max_pixels' => 30000000, // 30 MP equivalent to an image 6000 x 5000 / 0 = no limit
'image_resize_min_ratio' => 1.5, // min size diff original vs resize. Only resizes if ratio > min ratio
'image_resize_cache_direct' => false, // if enabled and delete cache, must increase cache_key
'folder_preview_image' => true, // enable folder preview images / might be slow as it requires searching each dir for images
'folder_preview_default' => '_filespreview.jpg', // use this image as folder preview if exists in dir
// menu
'menu_enabled' => true,
'menu_show' => true,
'menu_max_depth' => 5,
'menu_sort' => 'name_asc', // name_asc, name_desc, date_asc, date_desc
'menu_cache_validate' => true,
'menu_load_all' => true,
'menu_recursive_symlinks' => true, // List sub-directories of symlinks in the main menu. May cause loops and duplicates
// files layout
'layout' => 'rows', // list, imagelist, blocks, grid, rows, columns
'sort' => 'name_asc', // name, date, filesize, kind / asc, desc
'sort_dirs_first' => true, // sort dirs on top
// cache
'cache' => true,
'cache_key' => 0,
'storage_path' => 'src',
// exclude files directories regex
'files_exclude' => '', // '/\.(pdf|jpe?g)$/i'
'dirs_exclude' => '', //'/\/Convert|\/football|\/node_modules(\/|$)/i',
'allow_symlinks' => true, // allow symlinks
// various
'history' => true,
'breadcrumbs' => true,
'transitions' => true,
'click' => 'popup', // popup, modal, download, window, menu / default item click
'click_window' => '', // 'pdf, html, php, zip' / list of file extensions to open directly on click
'click_window_popup' => true, // Popup instead of new tab. Useful for viewing PDF, HTML and text type documents / desktop only
'code_max_load' => 100000, // max filesize of text files to load and preview
'topbar_sticky' => 'scroll', // true, false, 'scroll'
'check_updates' => true, // show notification in topbar with option to update when new version is available
'allow_tasks' => true,
'get_mime_type' => true, // get file mime type from server (slow) instead of from extension (fast)
'context_menu' => true, // disable context-menu button and right-click menu
'prevent_right_click' => false, // blocks browser right-click menu on sensitive items (images, list items, menu)
'license_key' => '',
'filter_live' => true, // live search filtering on keyboard input / does not apply for mobile devices
'filter_props' => 'name, filetype, mime, features, title', // file properties to filter / name, filetype, mime, features, title, headline, description, creator, credit, copyright, keywords, city, sub-location, province-state'
'download_dir' => 'zip', // download all files in folder / 'zip' / 'files' / '' false (disabled)
'download_dir_cache' => 'dir', // enable caching of created zip dirs / 'dir' / 'storage' / '' false (disabled)
// filemanager options
'allow_upload' => true, // allow uploader
'allow_delete' => true, // allow deleting files and folders
'allow_rename' => true, // allow renaming files and folders
'allow_new_folder' => true, // allow make new directory
'allow_new_file' => true, // allow make new empty file
'allow_duplicate' => true, // allow duplicate files
'allow_text_edit' => true, // allow editing text-based files in modal
'demo_mode' => false, // block all filemanager operations but allow them to show in interface / used in Files app demo
// uploader options
'upload_allowed_file_types' => '', // comma-separated list of allowed upload file types / empty = allow any / 'jpeg, jpg, image/*'
'upload_max_filesize' => 0, // [bytes] / 0 = unlimited (but limited by server PHP upload_max_filesize)
'upload_note' => '', // include a small text note at bottom of uploader / 'Max file size %upload_max_filesize%'
'upload_exists' => 'increment', // 'increment' / 'overwrite' / 'fail'
// popup options
'popup_video' => true, // opens videos in the popup (instead of modal)
'popup_transition' => 'glide', // none, slide, glide, fade, zoom, pop, elastic
'popup_transition_play' => 'inherit', // transition in play mode
'popup_interval' => 5000, // interval ms between slides in play mode
'popup_caption' => true, // enable popup caption
'popup_caption_hide' => true, // autohide popup caption after a few seconds without user input
'popup_caption_style' => 'block', // block, box, gradient, topbar, none
'popup_caption_align' => 'center-left', // left, center-left, center, right
// video
'video_thumbs' => true, // allow video thumbnails / requires FFmpeg and PHP exec() function enabled.
'video_ffmpeg_path' => 'ffmpeg', // path to ffmpeg command, normally 'ffmpeg' http://ffmpeg.org/
'video_autoplay' => true, // video autoplay on click
// language
'lang_default' => 'en', // default language if browser lang is not supported/detected or lang_auto is disabled
'lang_auto' => true, // automatically load language based on detected browser language
'lang_menu' => false, // display dropdown menu to select language
);
// config (will popuplate)
public static $config = array();
// app vars
static $__dir__ = __DIR__;
static $__file__ = __FILE__;
static $assets;
static $prod = true;
static $version = '0.3.1';
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;
// 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){
// BASIC DIAGNOSTICS
echo '<!doctype html><html><head><title>Files App check system and config.</title><meta name="robots" content="noindex,nofollow"><style>body{font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif; 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 App ' . 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>';
// 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
echo prop('storage_path exists', file_exists(config::$config['storage_path']));
if(file_exists(config::$config['storage_path'])) echo prop('storage_path is_writeable', is_writable(config::$config['storage_path']));
echo prop('root is_writeable', is_writable(config::$config['root']));
// extension_loaded
if(function_exists('extension_loaded')) foreach (['gd', 'exif'] 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));
// ffmpeg
if(function_exists('exec')) echo prop('ffmpeg', !!exec('type -P ' . config::$config['video_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;
}
// 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://forum.photo.gallery/viewtopic.php?f=66&t=9964' . 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);
// files check with ?check=true
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 / un-comment if you want to use
// CDN assets
self::$assets = self::$prod ? 'https://cdn.jsdelivr.net/npm/files.photo.gallery@' . self::$version . '/' : '';
// root
self::$root = real_path(self::$config['root']);
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'];
// X3 compatibility / x3 login / images from X3 resize cache / invalidate X3 cache on filemanager op / X3 license
$x3_path = dirname(self::$root);
self::$x3_path = file_exists($x3_path . '/app/x3.inc.php') ? $x3_path : false;
if(self::$x3_path && self::$username === 'x3'){
$x3_config = file_exists($x3_path . '/config/config.user.json') ? json_decode(file_get_contents($x3_path . '/config/config.user.json'), true) : false;
self::$username = isset($x3_config['back']['panel']['username']) ? $x3_config['back']['panel']['username'] : 'admin';
self::$password = isset($x3_config['back']['panel']['password']) ? $x3_config['back']['panel']['password'] : 'admin';
if(self::$username === 'admin' && self::$password === 'admin' && isset($x3_config['back']['panel']['use_db'])) error('Sorry, Files app is not compatible with X3 panel database login. Assign "username" and "password" separately in _files/config/config.php.', 403);
}
// 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;
}
// 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);
// login
if(self::$has_login) check_login($is_doc);
}
};
// login page
function login_page($is_login_attempt, $sidx, $is_logout, $client_hash){
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, viewport-fit=cover, user-scalable=no, shrink-to-fit=no">
<meta name="robots" content="noindex,nofollow">
<title>Login</title>
<link href="https://raw.githubusercontent.com/webelegan/cfm/main/src/files.css" rel="stylesheet">
<?php get_include('css/custom.css'); ?>
</head>
<body><div id="files-login-container"></div></body>
<script>
document.getElementById('files-login-container').innerHTML = '\
<h1 class="header mb-5">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>\
<div class="mylogin">\
<input type="text" name="username" placeholder="Username">\
<input type="password" name="password" placeholder="Password">\
</div>\
<input type="text" name="fusername" class="form-control form-control-lg mb-3" placeholder="Username" required autofocus spellcheck="false" autocorrect="off" autocapitalize="off">\
<input type="password" name="fpassword" class="form-control form-control-lg mb-3" placeholder="Password" required spellcheck="false">\
<input type="hidden" name="client_hash" value="<?php echo $client_hash; ?>">\
<input type="hidden" name="sidx" value="<?php echo $sidx; ?>">\
<input type="submit" value="Login" class="btn btn-lg btn-files-light btn-login">\
</form>';
document.getElementsByTagName('form')[0].addEventListener('submit', function(){
this.action = '<?php echo isset($_GET['logout']) ? strtok($_SERVER['REQUEST_URI'], '?') : $_SERVER['REQUEST_URI']; ?>';
this.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_start() && !$is_dor) error('Failed to initiate PHP session_start();', 500);
function get_client_hash(){
foreach(array('HTTP_CLIENT_IP','HTTP_X_FORWARDED_FOR','HTTP_X_FORWARDED','HTTP_FORWARDED_FOR','HTTP_FORWARDED','REMOTE_ADDR') as $key){
if(isset($_SERVER[$key]) && !empty($_SERVER[$key]) && filter_var($_SERVER[$key], FILTER_VALIDATE_IP)) return md5($_SERVER[$key] . $_SERVER['HTTP_USER_AGENT'] . __FILE__ . $_SERVER['HTTP_HOST']);
}
error('Invalid IP', 401);
}
// hash
$client_hash = get_client_hash();
$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']);
// correct login set $_SESSION['login']
if($is_login_attempt &&
trim($_POST['fusername']) == config::$username &&
(phpversion() >= 5.5 && !password_needs_rehash(config::$password, PASSWORD_DEFAULT) ? password_verify(trim($_POST['fpassword']), config::$password) : (trim($_POST['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 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 : '');
}
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 paths that start with /_files* (reserved for any files and folders to be ignored and hidden from Files app)
if(strpos($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);
}
}
// get file (proxy or resize image)
function get_file($path, $resize = 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);
foreach (array('video_thumbs', 'load_images', 'image_resize_cache', 'video_ffmpeg_path') as $key) if(empty(config::$config[$key])) error($key . ' option disabled.', 400);
if(!function_exists('exec')) error('PHP <a href="https://www.php.net/manual/en/function.exec.php" target="_blank">exec()</a> function is disabled on this server.', 400);
if(empty(exec('type -P ' . config::$config['video_ffmpeg_path']))) error('Can\'t find <a href="http://ffmpeg.org/" target="_blank">FFmpeg</a> in location "' . config::$config['video_ffmpeg_path'] . '".', 400);
// 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);
// ffmpeg command
$cmd = escapeshellarg(config::$config['video_ffmpeg_path']) . ' -i ' . escapeshellarg($path) . ' -deinterlace -an -ss 1 -t 1 -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);
// output created video thumbnail
read_file($cache, null, 'Video thumb created', null, true);
// 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);
// 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], null);
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
$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
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);
// 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);
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;
// https://github.com/maxim/smart_resize_image/blob/master/smart_resize_image.function.php
// https://github.com/gavmck/resize/blob/master/php/lib/resize-class.php
// https://github.com/gumlet/php-image-resize/blob/master/lib/ImageResize.php
// https://www.bitrepository.com/resize-an-image-keeping-its-aspect-ratio-using-php-and-gd.html
}
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);
// array
$arr = array(
'basename' => basename($realpath) ?: basename($path) ?: '',
'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']);
// download_dir cache direct access to zip / better caching and no need to access PHP / only works when download_dir_cache === 'dir'
/*if($url_path && config::$config['download_dir'] === 'zip' && config::$config['download_dir_cache'] === 'dir') {
$zip = $realpath . '/_files.zip';
if(file_exists($zip) && filemtime($zip) >= $filemtime) $arr['zip'] = get_url_path($zip);
}*/
}
// 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;
}
// 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
$subdirs = isset($data['files']) ? array_filter(array_map(function($file){
return $file['filetype'] === 'dir' ? root_absolute($file['path']) : false;
}, $data['files'])) : glob($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;
}
// get exif
function get_exif($path){
if(!function_exists('exif_read_data')) return;
$exif_data = @exif_read_data($path, 'ANY_TAG', 0); // @exif_read_data($path);
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) {
if(isset($exif_data[$name])) $exif[$name] = trim($exif_data[$name]);
}
if(isset($exif['DateTime'])) $exif['DateTime'] = @strtotime($exif['DateTime']);
if(isset($exif['DateTimeOriginal'])) $exif['DateTimeOriginal'] = @strtotime($exif['DateTimeOriginal']);
/*LensInfo 24-70mm f/?
Lens EF24-70mm f/2.8L USM
LensID 230*/
// 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
$gps = get_image_location($exif_data);
if(!empty($gps)) $exif['gps'] = $gps;
// return
return $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;
}
}
list($degrees, $minutes, $seconds) = $coordinate;
$sign = ($exif[$key.'Ref'] == 'W' || $exif[$key.'Ref'] == 'S') ? -1 : 1;
$arr[] = $sign * ($degrees + $minutes/60 + $seconds/3600);
}
return $arr;
}
// function get_image_location($exif){
// $arr = array('GPSLatitudeRef', 'GPSLatitude', 'GPSLongitudeRef', 'GPSLongitude');
// foreach ($arr as $val) {
// if(!isset($exif[$val])) return false;
// }
// $GPSLatitudeRef = $exif[$arr[0]];
// $GPSLatitude = $exif[$arr[1]];
// $GPSLongitudeRef= $exif[$arr[2]];
// $GPSLongitude = $exif[$arr[3]];
// $lat_degrees = count($GPSLatitude) > 0 ? gps2Num($GPSLatitude[0]) : 0;
// $lat_minutes = count($GPSLatitude) > 1 ? gps2Num($GPSLatitude[1]) : 0;
// $lat_seconds = count($GPSLatitude) > 2 ? gps2Num($GPSLatitude[2]) : 0;
// $lon_degrees = count($GPSLongitude) > 0 ? gps2Num($GPSLongitude[0]) : 0;
// $lon_minutes = count($GPSLongitude) > 1 ? gps2Num($GPSLongitude[1]) : 0;
// $lon_seconds = count($GPSLongitude) > 2 ? gps2Num($GPSLongitude[2]) : 0;
// $lat_direction = ($GPSLatitudeRef == 'W' or $GPSLatitudeRef == 'S') ? -1 : 1;
// $lon_direction = ($GPSLongitudeRef == 'W' or $GPSLongitudeRef == 'S') ? -1 : 1;
// $latitude = $lat_direction * ($lat_degrees + ($lat_minutes / 60) + ($lat_seconds / (60*60)));
// $longitude = $lon_direction * ($lon_degrees + ($lon_minutes / 60) + ($lon_seconds / (60*60)));
// return array($latitude, $longitude);
// }
function gps2Num($coordPart){
$parts = explode('/', $coordPart);
if(count($parts) <= 0) return 0;
if(count($parts) == 1) return $parts[0];
if($parts[1] == 0) return 0;
return floatval($parts[0]) / floatval($parts[1]);
}
//
function get_files_data($dir, $url_path = false, &$dirsize = 0, &$files_count = 0, &$images_count = 0, &$preview = false){
// scandir
$filenames = scandir($dir, SCANDIR_SORT_NONE);
if(empty($filenames)) return array();
$items = array();
// look for folder_preview_default (might be excluded in loop)
if(config::$config['folder_preview_default'] && in_array(config::$config['folder_preview_default'], $filenames)) $preview = config::$config['folder_preview_default'];
// loop filenames
foreach($filenames as $filename) {
//
if($filename === '.' || $filename === '..') continue;
$path = $dir . '/' . $filename;
// paths
$realpath = real_path($path); // differs from $path only if is symlinked