Repository navigation
Expand file tree
/
Copy pathfolder-explorer.php
More file actions
4762 lines (4513 loc) · 357 KB
/
Copy pathfolder-explorer.php
File metadata and controls
4762 lines (4513 loc) · 357 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php $DocFil= 'folder-explorer.php'; $DocVer='2.4.2'; $DocRev='2026-10-25'; $DocIni='evs'; $ModulNr=0; ## File informative only
$©= '𝘓𝘐𝘊𝘌𝘕𝘚𝘌 & 𝘊𝘰𝘱𝘺𝘳𝘪𝘨𝘩𝘵 © 2019-26 EV-soft *** Built with <a href="https://github.com/EV-soft/Clever-Html-Engine" target="_blank" rel="noopener">php2html - Clever HTML Engine</a>';
define('FE_VERSION', $DocVer); define('FE_DATE', $DocRev); define('FE_FOOTER', $©); // Kept: the library overwrites $DocVer, $DocRev and $© when it is included
## Libraries (jQuery, Tablesorter, Font Awesome ...): automatic - php2html loads what a page uses (the login page: no table, no jQuery).
## To force one: $needJquery= '2'; ('0' off, '1' local, '2' CDN) - or $gbl_AutoLibs= false; for the old way (only what is set).
// The bundled library (php2html 1.8.0 - with p2h_audit.inc.php and p2h_trans.inc.php) - the calls in this file need 1.8 (an older shared copy in ../p2h/ would fail):
require_once (__DIR__.'/php2html.lib.php'); // Creating HTML-functions
## The activity log (program menu: Activity log - administrators): who did what, when and from where. A PHP file: opened in the browser it shows nothing.
$gbl_AuditFile= $gbl_AuditFile ?? __DIR__.'/fe-audit.log.php';
require_once (__DIR__.'/p2h_audit.inc.php');
## The translations (program menu: Translations - administrators): the texts of the program in other languages (_trans.sys.json)
$gbl_TransFile= $gbl_TransFile ?? __DIR__.'/_trans.sys.json';
require_once (__DIR__.'/p2h_trans.inc.php');
##### SPECIAL this page only:
define ('p2h_IS_WIN', DIRECTORY_SEPARATOR == '\\');
define ('p2h_PATH', ''); // $p); // $p = pathinfo($p)['dirname'];
defined('p2h_ICONV_INPUT_ENC') || define('p2h_ICONV_INPUT_ENC', 'UTF-8'); // PHP 7.1+ uses UTF-8 filenames on Windows too
$is_https = isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1)
|| isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https';
defined('p2h_SELF_URL') || define('p2h_SELF_URL', ($is_https ? 'https' : 'http'). '://' . $_SERVER['HTTP_HOST']. $_SERVER['PHP_SELF']);
defined('p2h_SHOW_HIDDEN') || define('p2h_SHOW_HIDDEN', $show_hidden_files?? '');
defined('p2h_ROOT_PATH') || define('p2h_ROOT_PATH', $p2h_AppConf['root_path']?? '');
defined('p2h_LANG') || define('p2h_LANG', $lang?? '');
defined('p2h_FILE_EXTENSION') || define('p2h_FILE_EXTENSION', $p2h_AppConf['allowed_file_extensions']?? '');
defined('p2h_UPLOAD_EXTENSION') || define('p2h_UPLOAD_EXTENSION', $p2h_AppConf['allowed_upload_extensions']?? '');
defined('p2h_EXCLUDE_ITEMS') || define('p2h_EXCLUDE_ITEMS', $p2h_AppConf['exclude_items']?? '');
defined('p2h_DOC_VIEWER') || define('p2h_DOC_VIEWER', $p2h_AppConf['online_viewer']?? '');
define ('p2h_READONLY', ($p2h_AppConf['use_auth'] ?? false)
&& !empty($p2h_AppConf['readonly_users'])
&& isset($_SESSION[p2h_SESSION_ID]['logged'])
&& in_array($_SESSION[p2h_SESSION_ID]['logged'],
$p2h_AppConf['readonly_users']));
define ('p2h_USER_PATH', $p2h_AppConf['myPlace']?? '');
define ('MAX_UPLOAD_SIZE', $p2h_AppConf['max_upload_size_bytes']?? '');
if ( !defined( 'p2h_SESSION_ID')) { define('p2h_SESSION_ID', 'foldermanager'); }
// session_name(p2h_SESSION_ID );
$auth_users = array( # hash # userPath # userRights # Write folders (below $fe_root_path, '' = all of it)
'fe-admin' => ['$2y$10$g9W04bYhFOG45HAvnZCK6.FytNiDdzW4OM6Si0L4SaJAm/LyZa.zG','root','rwx', ['']], // xxxxxxxx
'fe-user' => ['$2y$10$vJjLTMo9Zb2oIhd.RF.W8eXsVWfFXVdze4Ta7WC7xAQZb8LtDLoH6','root','rwx', ['_exchange']], // xxxxxxxx
'visitor' => ['$2y$10$kD49SD5o81IAU1sU/k8e3.59T9ZiGfzgG9jWpc./Y04V6B1hHzP/a','root','r', []] // 8x x - public demo account: read only
); # Accounts are made in the program: program menu (right-click the table) - Users. They are saved in fe-users.php, which then replaces this list.
# userRights: r: download / see the content of files in the write folders and the shared folder ($fe_exchange_path)
# w: upload, copy, move, rename, ZIP, unpack and delete - only in the write folders (4th field; missing = the shared folder)
# A write folder that does not exist is created and closed for direct web access (.htaccess) - an existing folder is used as it is:
# files uploaded to a folder the web server shows can be opened directly in the browser.
## Long work (Analyse, the folder sizes of the tree, copy / ZIP of big folders): PHP's time limit (max_execution_time) is
## extended while the work goes on - up to this total in seconds. The web server may have its own limit.
$fe_max_time= $fe_max_time ?? 300;
$gbl_SessionKeep= $gbl_SessionKeep ?? true; // true: an open page keeps the login alive (no session timeout) - false: logged out after session.gc_maxlifetime without activity (a dialog warns)
## Browsing is restricted to this folder and its subfolders (no access above it):
$fe_root_path= $fe_root_path ?? __DIR__;
## The shared folder: created automatically, closed for direct web access (.htaccess) - files are only served through this page.
## Accounts with the right r may download from it, and it is the write folder of an account with w without its own list.
$fe_exchange_path= $fe_exchange_path ?? $fe_root_path.'/_exchange';
$fe_max_upload= $fe_max_upload ?? 20 * 1024 * 1024; // Max size per file (bytes) - PHP's upload_max_filesize / post_max_size also apply
$fe_exchange_quota= $fe_exchange_quota ?? 200 * 1024 * 1024; // Max total size of the shared folder (bytes) - other write folders have no quota of their own
## The trash: deleted files and folders are moved here - a hidden folder, closed for direct web access and never shown in the tree.
## Program menu - Trash: restore them, or delete them for good. After $fe_trash_days days they are deleted for good, and when the trash
## holds more than $fe_trash_max bytes the oldest go first. $fe_trash_days= 0: no trash - deleted at once.
$fe_trash_path= $fe_trash_path ?? __DIR__.'/.fe-trash';
$fe_trash_days= $fe_trash_days ?? 30;
$fe_trash_max= $fe_trash_max ?? 500 * 1024 * 1024;
## Share links (file menu: Share link): a link to a file - or a folder, fetched as a ZIP - for people without an account, with an end date and maybe a password.
## Accounts with the right w make them for what they may download - and a link only works while its maker may still download it.
## Program menu - Shared links: see, copy and delete them. $fe_share_days= 0: no share links.
$fe_shares_file= $fe_shares_file ?? __DIR__.'/fe-shares.php';
$fe_share_days= $fe_share_days ?? 90; // The longest time a link may work (days) - administrators may also make a link without an end
## TinyMCE (file menu of an HTML file: Edit with TinyMCE): fetched from here the first time it is used, not on every page - '' = not offered.
## Without internet access: put TinyMCE in _assets/tinymce/ and write '_assets/tinymce/' here (and '' for the languages: English).
$fe_tinymce_url= $fe_tinymce_url ?? 'https://cdnjs.cloudflare.com/ajax/libs/tinymce/8.9.3/';
$fe_tinymce_lang= $fe_tinymce_lang ?? 'https://cdn.jsdelivr.net/npm/tinymce-i18n@26.9.28/langs8/'; // The language packs of TinyMCE - '' = English
## "Remove restrictions" (admins only, per session): browse, download and write everywhere below $fe_unlocked_root,
## any file type (never hidden files like .htaccess) and no quota / size limit of its own.
$fe_admins= $fe_admins ?? ['fe-admin'];
$fe_unlocked_root= $fe_unlocked_root ?? dirname(p2h_norm_path($_SERVER['DOCUMENT_ROOT'] ?? __DIR__)); // e.g. /home/<account>
## Accounts made in the program (program menu: Users) - when this file exists, it replaces $auth_users and $fe_admins above.
## A PHP file: opened in the browser it shows nothing. It holds password hashes only.
$fe_users_file= $fe_users_file ?? __DIR__.'/fe-users.php';
if (is_file($fe_users_file)) {
try { $fe_ud= @include $fe_users_file; }
catch (Throwable $e) { $fe_ud= null; $fe_users_broken= true; } // A broken file: the accounts above are used - see the Users card
if (is_array($fe_ud) && !empty($fe_ud['users']) && is_array($fe_ud['users'])) { $auth_users= $fe_ud['users']; $fe_admins= $fe_ud['admins'] ?? $fe_admins; }
unset($fe_ud);
}
function p2h_js($str) { // Encode a PHP string as a safe JavaScript string literal
return json_encode((string)$str, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
}
function p2h_norm_path($path) { // Unified slashes, no trailing slash - but "/" stays "/"
$p= rtrim(str_replace('\\', '/', (string)$path), '/');
return $p === '' && $path !== '' && $path !== null ? '/' : $p;
}
function p2h_safe_path($requested, $root) { // Resolve $requested and accept it only inside $root
$root = p2h_norm_path(realpath($root) ?: $root);
if ($requested === null || $requested === '') return $root;
$real = realpath($requested);
if ($real === false) $real = realpath('/'. ltrim($requested, '/'));
if ($real === false || !is_dir($real)) return $root;
$real = p2h_norm_path($real);
return ($real === $root || strpos($real.'/', rtrim($root, '/').'/') === 0) ? $real : $root;
}
function fe_in_dir($path, $dir) { // Is $path the folder $dir or below it (both normalized)
return $dir !== false && $dir !== '' && ($path === $dir || strpos($path.'/', rtrim($dir, '/').'/') === 0);
}
function fe_can($right) { // Rights of the logged user: r= read (download, content), w= write (upload, copy, move, delete) - where: fe_can_read(), fe_can_write()
global $auth_users;
if (empty($auth_users)) return true;
$usr= $_SESSION[p2h_SESSION_ID]['logged'] ?? '';
return isset($auth_users[$usr][2]) && strpos($auth_users[$usr][2], $right) !== false;
}
function fe_exchange_init($dir) { // Create the exchange folder - closed for direct web access
if (!is_dir($dir) && !@mkdir($dir, 0755, true)) return false;
if (!is_file($dir.'/.htaccess'))
@file_put_contents($dir.'/.htaccess',
"# Folder-explorer exchange area: files are only served through folder-explorer.php\n".
"<IfModule mod_authz_core.c>\n Require all denied\n</IfModule>\n".
"<IfModule !mod_authz_core.c>\n Order allow,deny\n Deny from all\n</IfModule>\n");
if (!is_file($dir.'/index.html')) @file_put_contents($dir.'/index.html', '');
$real= realpath($dir);
return $real === false ? false : p2h_norm_path($real);
}
function fe_more_time() { // Called in long loops: every 10 s of work PHP's time limit starts again - until $fe_max_time in total
static $start= null, $last= 0.0, $orig= null;
if ($orig === null) $orig= (int)ini_get('max_execution_time');
if ($orig === 0) return; // No limit at all (CLI, or the server's setting): never set one
$now= microtime(true);
if ($now - $last < 10) return;
$last= $now;
if ($start === null) $start= $_SERVER['REQUEST_TIME_FLOAT'] ?? $now;
$left= ($GLOBALS['fe_max_time'] ?? 300) - ($now - $start);
if ($left > 1 && function_exists('set_time_limit')) @set_time_limit(max($orig, (int)min(30, ceil($left)))); // Never shorter than the server's own limit
}
function fe_show_path($path) { // A path to show: "root/sub/x" - the whole server path only when the restrictions are removed
global $fe_unlocked, $root_path;
$path= p2h_norm_path((string)$path);
if (!empty($fe_unlocked) || !fe_in_dir($path, (string)$root_path)) return $path === '' ? '/' : $path;
return rtrim(basename($root_path).'/'.ltrim(substr($path, strlen($root_path)), '/'), '/');
}
function fe_resolve_dest_new($raw) { // A destination - a new last folder is made, when the folder above it may be written in (one level)
$d= fe_resolve_dest($raw);
if ($d !== false) return $d;
$raw= rtrim(trim(str_replace('\\', '/', (string)$raw)), '/');
$pos= strrpos($raw, '/');
if ($pos === false) return false;
$parent= fe_resolve_dest(substr($raw, 0, $pos));
$name= fe_clean_name(substr($raw, $pos + 1));
if ($parent === false || $name === '' || $name[0] === '.' || !fe_can('w') || !fe_can_write($parent)) return false;
if (!is_dir($parent.'/'.$name) && !@mkdir($parent.'/'.$name, 0755)) return false;
return p2h_norm_path(realpath($parent.'/'.$name) ?: '') ?: false;
}
function fe_resolve_dest($raw) { // A destination folder: "root/sub" (as shown), "sub" (below the root) or a whole path - '' = the current folder, false = not found
global $root_path, $currPath;
$raw= trim(str_replace('\\', '/', (string)$raw));
if ($raw === '') return $currPath;
$rn= basename($root_path); $tries= [];
if ($raw === $rn || strpos($raw, $rn.'/') === 0) $tries[]= $root_path.'/'.substr($raw, strlen($rn)); // As shown on the page
$tries[]= $root_path.'/'.ltrim($raw, '/'); // Below the root
if (preg_match('#^(/|[a-z]:/)#i', $raw)) $tries[]= $raw; // A whole path
foreach ($tries as $t) {
$d= realpath($t);
if ($d !== false && is_dir($d) && fe_in_dir(p2h_norm_path($d), $root_path) && !fe_is_trash($d)) return p2h_norm_path($d);
}
return false;
}
function fe_hidden_below($path, $dir) { // A hidden folder or file (.git, .htaccess ...) between $dir and $path
foreach (explode('/', trim(substr($path, strlen($dir)), '/')) as $part) if ($part !== '' && $part[0] === '.') return true;
return false;
}
function fe_write_dirs() { // The folders where the logged user may write - normalized (unlocked admin: everything)
global $auth_users, $fe_root_path, $fe_exchange_path, $fe_unlocked, $root_path;
static $dirs= null;
if ($dirs !== null) return $dirs;
$dirs= [];
if (!fe_can('w')) return $dirs;
if (!empty($fe_unlocked)) return $dirs= [$root_path];
$usr= $_SESSION[p2h_SESSION_ID]['logged'] ?? '';
$base= p2h_norm_path(realpath($fe_root_path) ?: $fe_root_path);
foreach ($auth_users[$usr][3] ?? [ltrim(substr(p2h_norm_path(realpath($fe_exchange_path) ?: $fe_exchange_path), strlen($base)), '/')] as $rel) {
$rel= trim(str_replace('\\', '/', (string)$rel), '/');
if ($rel !== '' && preg_match('#(^|/)\.#', $rel)) continue; // Never a hidden folder - or ..
$d= $rel === '' ? $base : (is_dir($base.'/'.$rel) ? p2h_norm_path(realpath($base.'/'.$rel)) : fe_exchange_init($base.'/'.$rel));
if ($d !== false && fe_in_dir($d, $base)) $dirs[]= $d;
}
return $dirs;
}
function fe_can_write($dir) { // May the logged user write in the folder $dir
if (!is_string($dir) || $dir === '') return false;
foreach (fe_write_dirs() as $w)
if (fe_in_dir($dir, $w) && (!empty($GLOBALS['fe_unlocked']) || !fe_hidden_below($dir, $w))) return true;
return false;
}
function fe_can_read($file) { // May the logged user download / see the content of $file: in the write folders and the shared folder
global $fe_unlocked, $root_path, $exch_path;
$file= p2h_norm_path((string)$file);
$real= realpath($file); // A link must not lead out of the root
if ($real === false || !fe_in_dir(p2h_norm_path($real), $root_path)) return false;
if (!empty($fe_unlocked)) return fe_in_dir($file, $root_path);
if (!fe_name_allowed(basename($file))) return false;
$dirs= fe_write_dirs();
if (fe_can('r') && $exch_path) $dirs[]= $exch_path;
foreach ($dirs as $d) if (fe_in_dir($file, $d) && !fe_hidden_below($file, $d)) return true;
return false;
}
function fe_conf_init() { // A taken name (POST fe_conf): ask (the answers per name in fe_ch), rename "name (2)", overwrite (the old file into the trash), skip
$m= (string)($_POST['fe_conf'] ?? 'rename'); // Without it (no JavaScript): "name (2)" - nothing is overwritten
$GLOBALS['fe_conf']= in_array($m, ['ask', 'rename', 'overwrite', 'skip'], true) ? $m : 'rename';
$ch= json_decode((string)($_POST['fe_ch'] ?? ''), true);
$GLOBALS['fe_ch']= is_array($ch) ? array_filter($ch, fn($v) => in_array($v, ['rename', 'overwrite', 'skip'], true)) : [];
$a= (string)($_POST['fe_chall'] ?? ''); // The choice of All - for the names not in the list (more than the dialog shows)
$GLOBALS['fe_chall']= in_array($a, ['rename', 'overwrite', 'skip'], true) ? $a : 'rename';
}
function fe_choice($key) { // What to do with the taken name $key: rename / overwrite / skip - asked, but not in the answers: the choice of All (none: rename)
$m= $GLOBALS['fe_conf'] ?? 'rename';
return $m === 'ask' ? ($GLOBALS['fe_ch'][$key] ?? $GLOBALS['fe_chall'] ?? 'rename') : $m;
}
function fe_up_repl($base, $rel, $name) { // Upload: the bytes of the file it will overwrite (0: none) - for the quota of the shared folder
$d= fe_rel_dir($base, $rel, false);
$t= $d === false ? '' : $d.'/'.$name;
return ($t !== '' && is_file($t) && !is_link($t) && !fe_made($t) && fe_choice(ltrim(substr($t, strlen($base)), '/')) === 'overwrite') ? (int)filesize($t) : 0;
}
function fe_made($path= null) { // Made by this request: a second item of the same name (two folders in the basket, twice in a ZIP) never replaces the first - null: is it?
static $made= [];
$k= p2h_norm_path((string)$path);
if (in_array(PHP_OS_FAMILY, ['Windows', 'Darwin'], true)) $k= strtolower($k); // There A.txt and a.txt are the same file - on Linux two files
if (func_num_args() === 2) { $made[$k]= 1; return true; }
return isset($made[$k]);
}
function fe_check_answer($list) { // The precheck of "Stop and ask": the taken names as JSON - nothing is done
while (ob_get_level()) ob_end_clean();
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['c' => array_values(array_slice($list, 0, 500))], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
exit;
}
function fe_conflict($key, $new, $there, $size= null, $time= null) { // One taken name for the dialog: k key, d 1 = two folders (merged) - x 1 = a file against a folder (only "name (2)"), a / b [size, time] of the new / the one there
$dn= is_dir($new); $dt= is_dir($there);
$st= fn($p, $d) => $d ? [null, @filemtime($p) ?: null] : [@filesize($p), @filemtime($p) ?: null];
return ['k' => $key, 'd' => $dn && $dt ? 1 : 0, 'x' => ($dn !== $dt || is_link($there) || ($new !== '' && fe_same($new, $there))) ? 1 : 0,
'a' => $new === '' ? [$size, $time] : $st($new, $dn), 'b' => $st($there, $dt)];
}
function fe_same($a, $b) { // The same file or folder (also with other upper / lower case on Windows)
$ra= realpath($a); $rb= realpath($b);
return $ra !== false && $rb !== false && strtolower(p2h_norm_path($ra)) === strtolower(p2h_norm_path($rb)) && @fileinode($ra) === @fileinode($rb);
}
function fe_old_away($path) { // Overwrite: the old file into the trash (without a trash: deleted) - false: it stays (a folder, a link, a protected file)
if (!is_file($path) || is_link($path) || (empty($GLOBALS['fe_unlocked']) && !fe_name_allowed(basename($path))) || fe_program_file($path)) return false;
$tn= 0; $ts= 0; $GLOBALS['fe_trash_big']= false;
$inTrash= fe_trash_put($path, $tn, $ts);
if (!$inTrash) @unlink($path);
if (file_exists($path)) return false;
if ($inTrash && !empty($GLOBALS['fe_trash_big'])) $GLOBALS['fe_gone'][]= basename($path); // Bigger than the trash: deleted for good
else $GLOBALS['fe_over'][]= basename($path);
return true;
}
function fe_kept($path) { // Skip: the name was taken - the one there is kept (not an error)
$GLOBALS['fe_kept'][]= basename($path);
}
function fe_zip_name($dir, $base) { // A new ZIP "name.zip" in $dir - never a name upload and rename refuse: a folder "x.php" gave "x.php.zip" (Apache may run it as PHP)
$n= fe_clean_name($base.'.zip');
if (!fe_name_allowed($n)) $n= str_replace('.', '_', fe_clean_name($base)).'.zip';
return fe_unique($dir.'/'.$n);
}
function fe_unique($target) { // Never overwrite: "name (2).ext" - "folder (2)" - a link (also a broken one) counts as there
if (!file_exists($target) && !is_link($target)) return $target;
$dir= dirname($target); $b= pathinfo($target, PATHINFO_FILENAME); $e= pathinfo($target, PATHINFO_EXTENSION);
if (is_dir($target)) { $b= basename($target); $e= ''; }
for ($n= 2; ; $n++) { $t= $dir.'/'.$b.' ('.$n.')'.($e > '' ? '.'.$e : ''); if (!file_exists($t) && !is_link($t)) return $t; }
}
function fe_renamed($old, $new) { // Remember that a name was taken: "a.pdf" was saved as "a (2).pdf" - shown by fe_renamed_note()
if (basename($old) !== basename($new)) $GLOBALS['fe_renamed'][]= [basename($old), basename($new)];
}
function fe_renamed_note() { // "<br>The name was taken - saved as: a.pdf → a (2).pdf, ..." - and what was overwritten / kept - at most 5 of each - empty: none
$five= fn($l) => implode(', ', array_slice($l, 0, 5)).(count($l) > 5 ? ' (+'.(count($l) - 5).')' : '');
$out= '';
if ($r= $GLOBALS['fe_renamed'] ?? [])
$out.= '<br>'.p2h_enc(lang('@The name was taken - saved as')).': '.$five(array_map(fn($p) => '<b>'.p2h_enc($p[0]).'</b> → <b>'.p2h_enc($p[1]).'</b>', $r));
if ($o= $GLOBALS['fe_over'] ?? [])
$out.= '<br>'.p2h_enc(lang(fe_trash_dir() !== false ? '@Overwritten - the old one is in the trash' : '@Overwritten')).': '.$five(array_map(fn($x) => '<b>'.p2h_enc($x).'</b>', $o));
if ($g= $GLOBALS['fe_gone'] ?? [])
$out.= '<br>'.p2h_enc(lang('@Overwritten - the old one was too big for the trash and is deleted')).': '.$five(array_map(fn($x) => '<b>'.p2h_enc($x).'</b>', $g));
if ($k= $GLOBALS['fe_kept'] ?? [])
$out.= '<br>'.p2h_enc(lang('@Skipped - the name was taken, the one there is kept')).': '.$five(array_map(fn($x) => '<b>'.p2h_enc($x).'</b>', $k));
return $out;
}
function fe_copy_tree($src, $dst, &$n, &$skip) { // Copy a file or a folder - only files the user may read - a taken name only in a merged folder ($GLOBALS['fe_merge']: overwrite / skip)
fe_more_time();
if (is_link($src)) { $skip++; return; } // Never a link: a loop - or files outside the root
if (is_dir($src)) {
if ((empty($GLOBALS['fe_unlocked']) && basename($src)[0] === '.') || fe_is_trash($src)) { $skip++; return; } // Hidden folders (.git ...) - the trash
if (is_link($dst) || (!is_dir($dst) && !@mkdir($dst, 0755))) { $skip++; return; }
foreach (scandir($src) ?: [] as $f) if ($f !== '.' && $f !== '..') fe_copy_tree($src.'/'.$f, $dst.'/'.$f, $n, $skip);
return;
}
if (!fe_can_read($src)) { $skip++; return; }
if (file_exists($dst) || is_link($dst)) { // In a folder that was there: as chosen for it
$m= $GLOBALS['fe_merge'] ?? '';
if ($m === 'skip' && is_file($dst) && !is_link($dst)) { fe_kept($dst); return; }
if ($m !== 'overwrite' || !fe_old_away($dst)) { $skip++; return; } // A folder, a link, a protected file: never replaced
}
if (!@copy($src, $dst)) { $skip++; return; }
@touch($dst, filemtime($src));
$n++;
}
function fe_move_tree($src, $dst, &$n, &$skip) { // Move a folder into a folder of the same name (merged): file by file, a taken name as chosen ($GLOBALS['fe_merge']) - the emptied folders are removed
fe_more_time();
if (is_link($src)) { $skip++; return; }
if (is_dir($src)) {
if (empty($GLOBALS['fe_unlocked']) && basename($src)[0] === '.') { $skip++; return; } // A hidden folder: stays
if (is_link($dst) || (!is_dir($dst) && (file_exists($dst) || !@mkdir($dst, 0755)))) { $skip++; return; }
foreach (scandir($src) ?: [] as $f) if ($f !== '.' && $f !== '..') fe_move_tree($src.'/'.$f, $dst.'/'.$f, $n, $skip);
$mt= @filemtime($src);
if (@rmdir($src) && $mt) @touch($dst, max($mt, (int)@filemtime($dst))); // Empty now - else something stayed (kept, protected)
return;
}
if ((empty($GLOBALS['fe_unlocked']) && !fe_name_allowed(basename($src))) || fe_program_file($src)) { $skip++; return; } // A protected file - or one of the program: stays
if (file_exists($dst) || is_link($dst)) {
$m= $GLOBALS['fe_merge'] ?? '';
if ($m === 'skip' && is_file($dst) && !is_link($dst)) { fe_kept($dst); return; } // It stays where it was
if ($m !== 'overwrite' || !fe_old_away($dst)) { $skip++; return; }
}
if (@rename($src, $dst)) $n++;
else $skip++;
}
function fe_conflicts_items($items, $dest, $op) { // "Stop and ask": the items whose name is taken in $dest (those fe_transfer() would not skip anyway)
$c= [];
foreach ($items as $src) {
foreach ($items as $o) if ($o !== $src && fe_in_dir($src, $o)) continue 2;
if (fe_in_dir($dest, $src) || ($op === 'move' && p2h_norm_path(dirname($src)) === $dest)) continue;
$dst= $dest.'/'.basename($src);
if (file_exists($dst) || is_link($dst)) $c[]= fe_conflict(basename($src), $src, $dst);
}
return $c;
}
function fe_transfer($items, $dest, $op, &$n, &$skip) { // Copy or move files / folders to the folder $dest - returns the moved items
global $fe_unlocked, $exch_path, $fe_exchange_quota;
$room= ($exch_path && fe_in_dir($dest, $exch_path) && empty($fe_unlocked)) ? $fe_exchange_quota - fe_dir_size($exch_path) : PHP_INT_MAX;
$done= [];
foreach ($items as $src) {
foreach ($items as $o) if ($o !== $src && fe_in_dir($src, $o)) continue 2; // Inside another of the items: comes with it
if (fe_in_dir($dest, $src) || ($op === 'move' && p2h_norm_path(dirname($src)) === $dest)) { $skip++; continue; } // Into itself - or moved where it is (a copy there: "name (2)")
$dst= $dest.'/'.basename($src); $how= 'new';
if (file_exists($dst) || is_link($dst)) { // The name is taken: as chosen - a file against a folder (or a link): only "name (2)"
$how= fe_choice(basename($src));
if (is_link($dst) || is_dir($dst) !== is_dir($src) || fe_same($dst, $src) || fe_made($dst)) $how= 'rename'; // (a copy in its own folder: never over itself - nor over what this request made)
if ($how === 'rename') $dst= fe_unique($dst);
elseif ($how === 'skip' && !is_dir($src)) { fe_kept($dst); continue; }
}
$merge= is_dir($src) && ($how === 'overwrite' || $how === 'skip'); // Two folders: merged - a taken file name inside as chosen
$repl= ($how === 'overwrite' && !$merge && is_file($dst) && !is_link($dst)) ? (int)filesize($dst) : 0; // Replaced: its bytes leave the folder (into the trash) - the quota counts the difference
if ($op === 'move' && $room !== PHP_INT_MAX && !fe_in_dir($src, $exch_path)) { // Into the shared folder from outside it: its quota
$size= is_dir($src) ? fe_dir_size($src) : filesize($src);
if ($size - $repl > $room) { $skip++; continue; }
$room-= $size - $repl;
}
if ($op === 'move' && fe_holds_program($src)) { $skip++; continue; } // The program itself: never moved
$GLOBALS['fe_merge']= $merge ? $how : '';
if ($op === 'move') {
if (!fe_can_write(p2h_norm_path(dirname($src))) || (empty($fe_unlocked) && (basename($src)[0] === '.' || (!is_dir($src) && !fe_name_allowed(basename($src))))) || (!is_dir($src) && fe_program_file($src)))
$skip++;
elseif ($merge) { fe_move_tree($src, $dst, $n, $skip); if (!file_exists($src)) $done[]= $src; fe_made($dst, true); }
elseif ($how === 'overwrite' && !fe_old_away($dst)) $skip++; // A protected file there: never replaced
elseif (@rename($src, $dst)) { $n++; $done[]= $src; fe_renamed($src, $dst); fe_made($dst, true); }
else $skip++;
} else {
$size= is_dir($src) ? fe_dir_size($src) : filesize($src);
if ($size - $repl > $room) { $skip++; continue; }
if ($how === 'overwrite' && !$merge && !fe_old_away($dst)) { $skip++; continue; }
fe_copy_tree($src, $dst, $n, $skip);
if (file_exists($dst)) { fe_renamed($src, $dst); fe_made($dst, true); }
$room-= $size - $repl;
}
$GLOBALS['fe_merge']= '';
}
fe_size_forget($dest); // The tree counts them again
foreach ($done as $d) fe_size_forget(dirname($d));
return $done;
}
function fe_sync_tree($src, $dst, &$n, &$skip) { // One way: copy what is missing or newer in $src to $dst - nothing is deleted, an older file is replaced
fe_more_time();
if (is_link($src) || is_link($dst)) { $skip++; return; } // Never a link: a loop - or files outside the root (also in the destination)
if (is_dir($src)) {
if ((empty($GLOBALS['fe_unlocked']) && basename($src)[0] === '.') || fe_is_trash($src)) { $skip++; return; } // Hidden folders (.git ...) - the trash
if (!is_dir($dst) && (file_exists($dst) || !@mkdir($dst, 0755))) { $skip++; return; }
foreach (scandir($src) ?: [] as $f) if ($f !== '.' && $f !== '..') fe_sync_tree($src.'/'.$f, $dst.'/'.$f, $n, $skip);
return;
}
if (!fe_can_read($src) || is_dir($dst)) { $skip++; return; }
if (is_file($dst)) {
if (filemtime($dst) >= filemtime($src)) return; // The same or newer there: kept
if ((empty($GLOBALS['fe_unlocked']) && !fe_name_allowed(basename($dst))) || fe_program_file($dst)) { $skip++; return; } // Never replace a protected file - or one of the program
}
if (@copy($src, $dst)) { @touch($dst, filemtime($src)); $n++; }
else $skip++;
}
function fe_sync_need($src, $dst) { // The bytes fe_sync_tree() would add: what is missing or newer in $src (for the quota of the shared folder)
fe_more_time();
if (is_link($src) || is_link($dst)) return 0;
if (is_dir($src)) {
if ((empty($GLOBALS['fe_unlocked']) && basename($src)[0] === '.') || fe_is_trash($src)) return 0;
$b= 0;
foreach (scandir($src) ?: [] as $f) if ($f !== '.' && $f !== '..') $b+= fe_sync_need($src.'/'.$f, $dst.'/'.$f);
return $b;
}
if (!fe_can_read($src) || is_dir($dst)) return 0;
if (is_file($dst)) return filemtime($dst) >= filemtime($src) ? 0 : max(0, (int)filesize($src) - (int)filesize($dst));
return (int)filesize($src);
}
function fe_delete_tree($path, &$n, &$skip) { // Delete a file, or a folder with its content - a folder with something protected left (.htaccess ...) stays
fe_more_time();
if (is_dir($path) && !is_link($path)) {
if (empty($GLOBALS['fe_unlocked']) && basename($path)[0] === '.') { $skip++; return; } // A hidden folder: kept
foreach (scandir($path) ?: [] as $f) if ($f !== '.' && $f !== '..') fe_delete_tree($path.'/'.$f, $n, $skip);
if (@rmdir($path)) $n++; else $skip++;
return;
}
if ((!empty($GLOBALS['fe_unlocked']) || fe_name_allowed(basename($path))) && !fe_program_file($path) && @unlink($path)) $n++;
else $skip++;
}
function fe_program_file($path) { // A file of the program (its PHP files, scripts, texts, accounts, _assets): never overwritten, deleted, moved or synchronized over - also without restrictions
static $list= null;
$r= realpath((string)$path);
if ($r === false) return false;
$low= fn($p) => strtolower(p2h_norm_path($p));
if ($list === null) {
$list= [];
foreach (array_merge(get_included_files(), glob(__DIR__.'/fe-*.js') ?: [], glob(__DIR__.'/_trans*.json') ?: [], [__DIR__.'/favicon.svg', (string)($GLOBALS['fe_users_file'] ?? ''), (string)($GLOBALS['fe_shares_file'] ?? '')]) as $f)
if ($f !== '' && ($x= realpath($f)) !== false) $list[$low($x)]= 1;
}
return isset($list[$low($r)]) || strpos($low($r).'/', $low(__DIR__.'/_assets').'/') === 0;
}
function fe_holds_program($path) { // The folder of the program - or a folder above it, or the trash: never deleted or moved (the program would be gone)
$p= p2h_norm_path((string)$path);
$t= fe_trash_dir();
return fe_in_dir(p2h_norm_path(__DIR__), $p) || ($t !== false && fe_in_dir($t, $p));
}
function fe_trash_dir() { // The trash folder - created and closed for direct web access - false: no trash
global $fe_trash_path, $fe_trash_days;
static $dir= null;
if ($dir === null) $dir= ((int)$fe_trash_days > 0 && is_string($fe_trash_path) && $fe_trash_path !== '') ? fe_exchange_init($fe_trash_path) : false;
return $dir;
}
function fe_is_trash($path) { // The trash folder - or below it: never shown, browsed, copied or zipped
$t= fe_trash_dir();
return $t !== false && fe_in_dir(p2h_norm_path($path), $t);
}
function fe_rm_all($path) { // Delete a folder of the program (in the trash) with all its content - a link is removed, never followed
if (is_dir($path) && !is_link($path)) {
foreach (scandir($path) ?: [] as $f) if ($f !== '.' && $f !== '..') fe_rm_all($path.'/'.$f);
return @rmdir($path);
}
return @unlink($path);
}
function fe_trash_move($path, $dst, &$n, &$skip) { // As fe_delete_tree() - but into the trash ($dst): what is protected stays where it is
fe_more_time();
if (is_dir($path) && !is_link($path)) {
if (empty($GLOBALS['fe_unlocked']) && basename($path)[0] === '.') { $skip++; return; } // A hidden folder: kept
if (!is_dir($dst) && !@mkdir($dst, 0755)) { $skip++; return; }
foreach (scandir($path) ?: [] as $f) if ($f !== '.' && $f !== '..') fe_trash_move($path.'/'.$f, $dst.'/'.$f, $n, $skip);
$mt= @filemtime($path);
if (@rmdir($path)) { $n++; if ($mt) @touch($dst, $mt); }
else $skip++;
return;
}
if ((!empty($GLOBALS['fe_unlocked']) || fe_name_allowed(basename($path))) && !fe_program_file($path) && @rename($path, $dst)) $n++;
else $skip++;
}
function fe_trash_put($path, &$n, &$skip) { // Delete: into the trash - false: no trash (the caller deletes it for good)
$t= fe_trash_dir();
if ($t === false) return false;
$id= date('Ymd-His').'-'.bin2hex(random_bytes(4));
if (!@mkdir($t.'/'.$id, 0755)) return false;
$n0= $n;
fe_trash_move($path, $t.'/'.$id.'/'.basename($path), $n, $skip);
if ($n === $n0) { fe_rm_all($t.'/'.$id); return true; } // Nothing of it could be moved
@file_put_contents($t.'/'.$id.'.json', json_encode(['n' => basename($path), 'f' => p2h_norm_path(dirname($path)),
'd' => is_dir($t.'/'.$id.'/'.basename($path)) ? 1 : 0, 'u' => $_SESSION[p2h_SESSION_ID]['logged'] ?? '', 't' => time(),
's' => fe_dir_size($t.'/'.$id)], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE));
fe_trash_trim();
if (!is_file($t.'/'.$id.'.json')) $GLOBALS['fe_trash_big']= true; // Bigger than the trash: deleted for good at once
return true;
}
function fe_trash_list() { // The trash, the newest first: id => [n name, f from folder, d 1 = a folder, u user, t time, s bytes]
$t= fe_trash_dir(); $list= [];
if ($t === false) return $list;
foreach (glob($t.'/*.json') ?: [] as $j) {
$id= basename($j, '.json');
$m= json_decode((string)@file_get_contents($j), true);
if (preg_match('/^\d{8}-\d{6}-[0-9a-f]{8}$/', $id) && is_array($m) && isset($m['n'], $m['f'], $m['t']) && is_string($m['n'])
&& !in_array($m['n'], ['', '.', '..'], true) && strpbrk($m['n'], "/\\\0") === false // One name - any name a file may have (not fe_clean_name(): a:b.txt was lost)
&& file_exists($t.'/'.$id.'/'.$m['n'])) $list[$id]= $m;
}
uasort($list, fn($a, $b) => $b['t'] <=> $a['t']);
return $list;
}
function fe_trash_drop($id) { // Delete one item of the trash for good
$t= fe_trash_dir();
if ($t === false || !preg_match('/^\d{8}-\d{6}-[0-9a-f]{8}$/', (string)$id)) return;
fe_rm_all($t.'/'.$id); @unlink($t.'/'.$id.'.json');
}
function fe_trash_trim() { // Away with the old ones - and the oldest, while the trash is too big - and what was left by a broken delete
global $fe_trash_days, $fe_trash_max;
$t= fe_trash_dir();
if ($t === false) return;
$list= fe_trash_list(); $sum= 0;
foreach ($list as $id => $m) { // The newest first
$sum+= (int)($m['s'] ?? 0);
if ($m['t'] < time() - (int)$fe_trash_days * 86400 || $sum > $fe_trash_max) { fe_trash_drop($id); unset($list[$id]); }
}
foreach (scandir($t) ?: [] as $f)
if (preg_match('/^(\d{8}-\d{6}-[0-9a-f]{8})(\.json)?$/', $f, $mm) && !isset($list[$mm[1]]) && @filemtime($t.'/'.$f) < time() - 3600) fe_rm_all($t.'/'.$f);
}
function fe_trash_may($m) { // May the logged user see / restore / delete this item of the trash: administrators all - others what came from their write folders
return fe_can('w') && (fe_is_admin() || fe_can_write((string)$m['f']));
}
function fe_trash_restore($id, $m) { // Back to its folder (made again, if it is gone) - a name taken there: "name (2)" - [true, new path] or [false, error]
global $exch_path, $fe_unlocked, $fe_exchange_quota;
$src= fe_trash_dir().'/'.$id.'/'.$m['n'];
if (!fe_can_write($m['f'])) return [false, lang('@You may not write in the folder').': '.fe_show_path($m['f'])];
if (empty($fe_unlocked) && empty($m['d']) && !fe_name_allowed($m['n'])) return [false, lang('@This file can not be changed here')];
if (!is_dir($m['f']) && !@mkdir($m['f'], 0755, true)) return [false, lang('@It could not be done')];
if ($exch_path && empty($fe_unlocked) && fe_in_dir($m['f'], $exch_path) && fe_dir_size($exch_path) + (int)($m['s'] ?? 0) > $fe_exchange_quota)
return [false, lang('@the shared folder is full')];
$dst= fe_unique($m['f'].'/'.$m['n']);
if (!@rename($src, $dst)) return [false, lang('@It could not be done')];
fe_trash_drop($id);
fe_size_forget($m['f']);
return [true, $dst];
}
function fe_zip_add($z, $path, $local, &$n, &$skip) { // Add a file or a folder to a ZIP - only files the user may read
fe_more_time();
if (is_link($path)) { $skip++; return; } // Never a link: a loop - or files outside the root
if ($n + $skip >= 20000) { $skip++; return; } // At most 20000 files - the rest is counted as skipped (and told)
if (is_dir($path)) {
if ((empty($GLOBALS['fe_unlocked']) && basename($path)[0] === '.') || fe_is_trash($path)) { $skip++; return; }
$z->addEmptyDir($local);
foreach (scandir($path) ?: [] as $f) if ($f !== '.' && $f !== '..') fe_zip_add($z, $path.'/'.$f, $local.'/'.$f, $n, $skip);
} elseif (fe_can_read($path) && $z->addFile($path, $local)) $n++;
else $skip++;
}
function fe_unzip($zip, $dest, $room, &$n, &$skip, $check= false) { // Unpack a ZIP in $dest: safe names only, at most $room bytes, a taken name as chosen - $check: only the taken names (nothing made)
if (!class_exists('ZipArchive')) return $check ? [] : false;
$z= new ZipArchive();
if ($z->open($zip, ZipArchive::RDONLY) !== true) return $check ? [] : false;
$total= 0; $taken= [];
for ($i= 0; $i < $z->numFiles; $i++) {
if ($i >= 20000) { $skip+= $z->numFiles - $i; break; }
fe_more_time();
$st= $z->statIndex($i);
$name= str_replace('\\', '/', $st['name']);
$isDir= substr($name, -1) === '/';
$parts= array_values(array_filter(explode('/', $name), 'strlen'));
$bad= !$parts || $name[0] === '/' || preg_match('#^[a-z]:#i', $name);
foreach ($parts as $part) if ($part[0] === '.') $bad= true; // .. and hidden files / folders
if ($bad || (!$isDir && !fe_name_allowed(end($parts)))) { $skip++; continue; }
$repl= 0; // A file it will overwrite: its bytes leave the folder
if (!$isDir && $room !== PHP_INT_MAX && ($d0= fe_rel_dir($dest, implode('/', $parts), false)) !== false && is_file($p0= $d0.'/'.fe_clean_name(end($parts)))
&& !is_link($p0) && !fe_made($p0) && fe_choice(ltrim(substr($p0, strlen($dest)), '/')) === 'overwrite') $repl= (int)filesize($p0);
if (!$isDir && $total + $st['size'] - $repl > $room) { $skip++; continue; } // Too large: skipped (not counted - a smaller file after it may fit), no folders made for it
$dir= fe_rel_dir($dest, implode('/', $parts).($isDir ? '/-' : ''), !$check);
if ($dir === false) { $skip++; continue; }
if ($isDir) continue;
$target= $dir.'/'.fe_clean_name(end($parts));
$key= ltrim(substr($target, strlen($dest)), '/'); // "sub/a.txt" - the same name in the dialog and here
if ($check) {
if (file_exists($target) || is_link($target)) $taken[]= fe_conflict($key, '', $target, (int)$st['size'], (int)$st['mtime']);
continue;
}
if (file_exists($target) || is_link($target)) {
$how= is_file($target) && !is_link($target) && !fe_made($target) ? fe_choice($key) : 'rename'; // A folder or a link of that name - or twice in the ZIP: "name (2)"
if ($how === 'skip') { fe_kept($target); continue; }
if ($how === 'overwrite' && !fe_old_away($target)) { $skip++; continue; }
if ($how === 'rename') $target= fe_unique($target);
}
$in= $z->getStream($st['name']);
$out= $in ? @fopen($target, 'xb') : false;
if (!$out) { if ($in) fclose($in); $skip++; continue; }
$total+= (int)stream_copy_to_stream($in, $out, $st['size']) - $repl; // Never more than the ZIP says (a false size in the ZIP)
fclose($in); fclose($out);
@touch($target, $st['mtime']);
fe_made($target, true);
$n++;
fe_renamed(fe_clean_name(end($parts)), $target);
}
$z->close();
return $check ? $taken : true;
}
function fe_clean_name($name) { // A plain file name: no path, no control or reserved characters
$name= str_replace('\\', '/', (string)$name);
$name= substr($name, strrpos('/'.$name, '/')); // The last part (not basename(): it takes "a:" for a drive on Windows - and depends on the locale)
$name= trim(preg_replace('/[\x00-\x1F\x7F<>:"\/\\\\|?*]/u', '_', $name) ?? '', " .");
if (DIRECTORY_SEPARATOR === '\\' && preg_match('/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i', $name)) $name= '_'.$name; // Windows: a device, not a file
return $name;
}
function fe_given_name($name) { // The name of an existing file or folder of the current folder - as it is (it may have characters a new name may not)
$name= (string)$name;
return ($name === '' || $name === '.' || $name === '..' || strpbrk($name, "/\\\0") !== false) ? '' : $name;
}
const FE_DENY_EXT= '\.(php\d*|phtml|phar|pht|phps|cgi|pl|py|sh|asp|aspx|jsp|htaccess|htpasswd|ini)(\.|$)'; // Also used by fe-upload.js
function fe_name_allowed($name) { // Never server scripts, server config or hidden files
if ($name === '' || $name[0] === '.') return false; // Hidden files (.htaccess ...) - also without restrictions
if ($GLOBALS['fe_unlocked'] ?? false) return true; // Admin has removed the restrictions
if (strcasecmp($name, 'index.html') === 0) return false;
return !preg_match('/'.FE_DENY_EXT.'/i', $name);
}
function fe_hint($html, $hint, $styl= '') { // The library hint (not the title tooltip of the browser) - opens just below $html
return '<abbr class="hint feHint"'.($styl > '' ? ' style="'.$styl.'"' : '').'>'.$html.'<data-hint>'.$hint.'</data-hint></abbr>';
}
function fe_is_admin() { // The logged user may remove the restrictions
return in_array($_SESSION[p2h_SESSION_ID]['logged'] ?? '', $GLOBALS['fe_admins'] ?? [], true);
}
function fe_send_file($file, $name= '') { // Send a file as a download, and stop
if (session_status() === PHP_SESSION_ACTIVE) session_write_close(); // A long download must not lock the other pages of the user
while (ob_get_level()) ob_end_clean();
$name= $name ?: basename($file);
$tmp= p2h_norm_path(sys_get_temp_dir());
fe_log('@Download', p2h_norm_path(dirname($file)) === $tmp ? $name : fe_show_path(p2h_norm_path($file)), // A ZIP made for it (a temp file): its name
html_entity_decode(p2h_nice_filesize(filesize($file)), ENT_QUOTES | ENT_HTML5, 'UTF-8'));
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.preg_replace('/[^\x20-\x7E]|"/', '_', $name).'"; filename*=UTF-8\'\''.rawurlencode($name));
header('Content-Length: '.filesize($file));
header('X-Content-Type-Options: nosniff');
header('Cache-Control: private, no-store');
readfile($file);
exit;
}
// Hover preview of a file icon (fe-preview.js) - extension => [kind, MIME type]
// img, video, audio, font: shown everywhere - txt, pdf, zip, doc: only where the file may be downloaded (else: lock)
const FE_PV_MEDIA= ['jpg'=>['img','image/jpeg'], 'jpeg'=>['img','image/jpeg'], 'png'=>['img','image/png'], 'gif'=>['img','image/gif'],
'webp'=>['img','image/webp'], 'bmp'=>['img','image/bmp'], 'ico'=>['img','image/x-icon'], 'svg'=>['img','image/svg+xml'], 'avif'=>['img','image/avif'],
'mp4'=>['video','video/mp4'], 'm4v'=>['video','video/mp4'], 'webm'=>['video','video/webm'], 'ogv'=>['video','video/ogg'], 'mov'=>['video','video/quicktime'],
'mp3'=>['audio','audio/mpeg'], 'wav'=>['audio','audio/wav'], 'ogg'=>['audio','audio/ogg'], 'oga'=>['audio','audio/ogg'], 'opus'=>['audio','audio/ogg'],
'm4a'=>['audio','audio/mp4'], 'aac'=>['audio','audio/aac'], 'flac'=>['audio','audio/flac'],
'ttf'=>['font','font/ttf'], 'otf'=>['font','font/otf'], 'woff'=>['font','font/woff'], 'woff2'=>['font','font/woff2'],
'jfif'=>['img','image/jpeg'], 'pjpeg'=>['img','image/jpeg'], 'apng'=>['img','image/apng'],
'mkv'=>['video','video/x-matroska'], 'weba'=>['audio','audio/webm'],
'pdf'=>['pdf','application/pdf'], 'zip'=>['zip',''], 'docx'=>['doc',''], 'odt'=>['doc',''], 'pptx'=>['doc',''], 'odp'=>['doc',''],
'rtf'=>['doc',''], 'epub'=>['doc',''],
'csv'=>['table',''], 'tsv'=>['table',''], 'xlsx'=>['table',''], 'ods'=>['table',''],
'tar'=>['arch',''], 'tgz'=>['arch',''], 'gz'=>['arch',''], 'tbz'=>['arch',''], 'bz2'=>['arch','']];
const FE_PV_TXT= ['txt','text','md','markdown','log','ini','cnf','conf','cfg','properties','toml','json','jsonc','map','webmanifest',
'eml','vcf','ics','m3u','m3u8','pls','cue','nfo','bib','ass','ssa','sub','gpx','kml','geojson','reg','gitattributes','lst','plist','xaml',
'resx','config','manifest','csproj','vbproj','sln','proto','graphql','gql','hbs','ejs','pug','haml','erb','coffee','elm','ex','exs','erl',
'hs','ml','clj','cljs','lisp','scm','f','f90','for','pas','asm','s','v','vhd','sv','cmake','nim','zig','jl','tf','hcl','nix','bas','au3','ahk',
'xml','xsl','xslt','yml','yaml','css','scss','sass','less','js','mjs','cjs','ts','tsx','jsx','vue','svelte','htm','html','xhtml','shtml',
'php','php3','php4','php5','php7','php8','phtml','inc','twig','tpl','mustache','sql','sh','bash','zsh','bat','cmd','ps1','py','rb','pl','pm',
'lua','java','kt','kts','swift','go','rs','c','h','cpp','hpp','cc','cxx','cs','vb','dart','scala','groovy','gradle','r','tex','rst',
'srt','vtt','diff','patch','htaccess','env','gitignore','editorconfig','lock','mk','makefile','dockerfile'];
function fe_temp_cleanup() { // Old temp files of the program: ZIPs never fetched (2 hours), counters of failed logins and folder sizes (a day)
$t= sys_get_temp_dir();
foreach ([['fez*', 7200], ['fe-login-*.txt', 86400], ['fe-size-*.txt', 86400], ['fe-thumb-*.jpg', 7 * 86400]] as [$pat, $age])
foreach (glob($t.'/'.$pat) ?: [] as $f) if (is_file($f) && @filemtime($f) < time() - $age) @unlink($f);
}
function fe_offer_download($file, $name, $temp, $note= '') { // A ZIP / file for the browser - fePost(.., true) gets a link (?fdl=), else it is sent at once
if ($temp && mt_rand(1, 10) === 1) fe_temp_cleanup(); // Now and then
if (($_POST['fe_ajax'] ?? '') === '1') {
$tok= bin2hex(random_bytes(12));
$_SESSION[p2h_SESSION_ID]['fdl'][$tok]= ['f' => $file, 'n' => $name, 't' => $temp, 'at' => time()];
while (ob_get_level()) ob_end_clean();
header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store');
exit(json_encode(['url' => basename(__FILE__).'?fdl='.$tok, 'note' => $note]));
}
if ($temp) register_shutdown_function(function() use ($file) { @unlink($file); });
fe_send_file($file, $name);
}
function fe_protected_dirs() { // The folders closed for direct web access by the program: the shared folder and the write folders of all accounts
global $auth_users, $fe_root_path, $exch_path;
static $dirs= null;
if ($dirs !== null) return $dirs;
$dirs= $exch_path ? [$exch_path] : [];
$base= p2h_norm_path(realpath($fe_root_path) ?: $fe_root_path);
foreach ($auth_users as $u) foreach ((array)($u[3] ?? []) as $rel) {
$rel= trim(str_replace('\\', '/', (string)$rel), '/');
if ($rel === '' || !($d= realpath($base.'/'.$rel))) continue; // '' = the whole root: not a protected folder
if (is_file($d.'/.htaccess')) $dirs[]= p2h_norm_path($d);
}
return $dirs;
}
function fe_media_ok($file) { // Images, video, audio, fonts: shown everywhere - but in a protected folder only to those who may read there
if (fe_can_read($file)) return true;
foreach (fe_protected_dirs() as $d) if (fe_in_dir(p2h_norm_path($file), $d)) return false;
return true;
}
function fe_looks_text($path) { // The start of a file looks like text: no NUL byte, UTF-8 (or a byte order mark) - for files without a known extension: error_log, LICENSE, x.log.1
$h= @file_get_contents($path, false, null, 0, 4096);
if (!is_string($h)) return false;
if (strncmp($h, "\xFF\xFE", 2) === 0 || strncmp($h, "\xFE\xFF", 2) === 0) return true; // UTF-16 with its mark (fe_bom() reads it)
if (strpos($h, "\0") !== false) return false;
if (strlen($h) === 4096) $h= substr($h, 0, strlen(mb_strcut($h, 0, 4093, 'UTF-8'))); // A character cut at the end of the 4 KB
return mb_check_encoding($h, 'UTF-8') || preg_match_all('/[\x00-\x08\x0E-\x1A\x1C-\x1F\x7F]/', $h) * 100 < strlen($h); // Or old 8-bit text: few control characters
}
function fe_preview_kind($name, $text_ok, $media_ok= true, $path= '') { // The kind of preview of a file - '' = none - $path: an unknown type is looked at (text or hex)
$ext= strtolower(pathinfo($name, PATHINFO_EXTENSION));
if ($ext === '' && in_array(strtolower($name), ['makefile','dockerfile','license','readme'], true)) $ext= 'txt';
$kind= FE_PV_MEDIA[$ext][0] ?? (in_array($ext, FE_PV_TXT, true) ? 'txt' : ($text_ok ? 'hex' : '')); // Any other file: its first bytes (hex)
if ($kind === 'hex' && $path !== '' && fe_looks_text($path)) $kind= 'txt'; // No type it knows - but the content is text (error_log ...)
if (in_array($kind, ['img','video','audio','font'], true) && !$media_ok) return 'lock';
if (in_array($kind, ['txt','pdf','zip','doc','table','arch'], true) && !$text_ok) return 'lock';
return $kind;
}
function fe_send_inline($file, $mime) { // Send a file to be shown in the page (preview) - HTTP Range for audio / video
$size= filesize($file); $from= 0; $to= $size - 1;
header('Content-Type: '.$mime);
header('Accept-Ranges: bytes');
if (preg_match('/^bytes=(\d*)-(\d*)$/', $_SERVER['HTTP_RANGE'] ?? '', $m) && ($m[1] !== '' || $m[2] !== '')) {
if ($m[1] === '') $from= max(0, $size - (int)$m[2]);
else { $from= (int)$m[1]; if ($m[2] !== '') $to= min($to, (int)$m[2]); }
if ($from > $to) { http_response_code(416); header('Content-Range: bytes */'.$size); exit; }
http_response_code(206);
header('Content-Range: bytes '.$from.'-'.$to.'/'.$size);
}
header('Content-Length: '.($to - $from + 1));
$h= fopen($file, 'rb'); fseek($h, $from); $left= $to - $from + 1;
while ($left > 0 && !feof($h) && !connection_aborted()) {
$part= fread($h, (int)min(65536, $left));
if ($part === false || $part === '') break;
echo $part; flush(); $left-= strlen($part);
}
fclose($h);
exit;
}
function fe_hexdump($data, $file= '') { // The first bytes of a file as hex + text - with its type when PHP knows it
$mime= ($file > '' && function_exists('finfo_open') && ($fi= @finfo_open(FILEINFO_MIME_TYPE))) ? (string)@finfo_file($fi, $file) : '';
$out= $mime > '' ? $mime."\n\n" : '';
for ($i= 0; $i < strlen($data); $i+= 16) {
$chunk= substr($data, $i, 16);
$out.= sprintf('%06x %-47s %s', $i, implode(' ', str_split(bin2hex($chunk), 2)), preg_replace('/[^\x20-\x7E]/', '.', $chunk))."\n";
}
return $out;
}
function fe_bom($txt) { // Text with a byte order mark: UTF-16 to UTF-8, and the mark away
if (strncmp($txt, "\xEF\xBB\xBF", 3) === 0) return substr($txt, 3);
foreach (["\xFF\xFE" => 'UTF-16LE', "\xFE\xFF" => 'UTF-16BE'] as $bom => $enc)
if (strncmp($txt, $bom, 2) === 0 && function_exists('iconv')) {
$body= substr($txt, 2); $body= substr($body, 0, strlen($body) - strlen($body) % 2);
return (string)iconv($enc, 'UTF-8//IGNORE', $body);
}
return $txt;
}
function fe_utf8($txt, $cut= false) { // Text as UTF-8 - $cut: only the start was read (a character cut at the end is removed) - other text is read as Windows-1252
for ($i= 0; $cut && $i < 3 && !preg_match('//u', $txt); $i++) $txt= substr($txt, 0, -1);
if (!preg_match('//u', $txt))
$txt= function_exists('iconv') ? (string)iconv('Windows-1252', 'UTF-8//IGNORE', $txt) : preg_replace('/[\x80-\xFF]/', '?', $txt);
return $txt;
}
function fe_rtf_drop($r) { // RTF: away with the groups that are no text: {\* ...}, font / colour tables, pictures ... - with braces inside them
$n= strlen($r); $out= ''; $i= 0;
while ($i < $n) {
if ($r[$i] === '{' && preg_match('~\G\{\\\\(\*|fonttbl|colortbl|stylesheet|info|pict|header|footer|listtable|listoverridetable|rsidtbl|xmlnstbl|latentstyles)~A', $r, $m, 0, $i)) {
$d= 0;
for ($j= $i; $j < $n; $j++) { // To the brace that closes the group
if ($r[$j] === '\\') { $j++; continue; }
if ($r[$j] === '{') $d++;
elseif ($r[$j] === '}' && --$d === 0) break;
}
$i= $j + 1; $out.= '{}'; // (an empty group: a control word before it ends there - nsi{...}Hej is not nsiHej)
continue;
}
$out.= $r[$i++];
}
return $out;
}
function fe_xml_text($xml) { // The text of an office XML part: paragraphs and line breaks kept, a table row on one line
$xml= substr($xml, 0, 4000000);
$xml= preg_replace(['#<w:del\b[^>]*>.*?</w:del>#s', '#<w:delText\b[^>]*>.*?</w:delText>#s', '#<w:instrText\b[^>]*>.*?</w:instrText>#s',
'#<text:tracked-changes\b.*?</text:tracked-changes>#s', '#<office:annotation\b.*?</office:annotation>#s', '#<office:annotation-end\b[^>]*/>#'],
'', $xml); // Deleted text (tracked changes), field codes and comments: not text
$xml= preg_replace_callback('#<text:s(?:\s+text:c="(\d+)")?\s*/>#', fn($m) => str_repeat(' ', min(200, max(1, (int)($m[1] ?? 1)))), $xml); // Spaces
$xml= preg_replace(['#</w:p>(\s*</w:tc>)#', '#</text:p>(\s*</table:table-cell>)#', // The last paragraph of a cell: no new line
'#</a:p>(\s*</a:txBody>\s*(?:<a:tcPr\b[^>]*/>|<a:tcPr\b.*?</a:tcPr>)?\s*</a:tc>)#s'], '$1', $xml);
$xml= preg_replace(['#</w:tc>|</table:table-cell>|</a:tc>#', '#</w:tr>|</table:table-row>|</a:tr>#'], ["\t", "\n"], $xml); // Cells / rows
$xml= preg_replace(['#<w:tab/>|<text:tab/>#', '#<w:br/>|<a:br/>|<text:line-break/>|</w:p>|</a:p>|</text:p>|</text:h>|</p>|</h[1-6]>|<br\s*/?>|</li>|</div>#i'], ["\t", "\n"], substr($xml, 0, 4000000));
$txt= html_entity_decode(strip_tags($xml), ENT_QUOTES | ENT_XML1 | ENT_HTML5, 'UTF-8');
return trim(preg_replace(["/\t+\n/", "/\n{3,}/"], ["\n", "\n\n"], $txt));
}
function fe_preview_text($file, $kind) { // Text for the preview: a text file, the list of an archive, the text of a document, or the first bytes (hex)
$ext= strtolower(pathinfo($file, PATHINFO_EXTENSION));
if ($kind === 'hex') return fe_hexdump((string)file_get_contents($file, false, null, 0, 512), $file);
if ($kind === 'doc' && $ext === 'rtf') { // RTF: the text without the control words
$r= (string)file_get_contents($file, false, null, 0, 400000);
$r= fe_rtf_drop($r); // Tables, pictures, {\* ...}: not text
$r= preg_replace_callback('~\\\\u(-?\d+) ?(?:\\\\\'[0-9a-f]{2}|\?)?~i', function($m) { // \u230? = æ (and its fallback after it)
$n= (int)$m[1]; if ($n < 0) $n+= 65536; return function_exists('mb_chr') ? (string)mb_chr($n, 'UTF-8') : '?'; }, $r);
$r= preg_replace_callback("~\\\\'([0-9a-f]{2})~i", function($m) { // \'e6 = æ (Windows-1252)
return function_exists('iconv') ? (string)iconv('Windows-1252', 'UTF-8//IGNORE', chr(hexdec($m[1]))) : '?'; }, $r);
$r= preg_replace(['~\\\\(par|line)\b ?~', '~\\\\tab\b ?~', '~\\\\[a-z]+-?\d* ?~i', '~[{}]~'], ["\n", "\t", '', ''], $r);
return substr(fe_utf8(trim(preg_replace("/\n{3,}/", "\n\n", $r))), 0, 16384);
}
if ($kind === 'arch') { // tar, tar.gz, tgz, tar.bz2 - a single .gz: its text
if (class_exists('PharData')) {
try {
$ph= new PharData($file); $rows= []; $n= 0; $sum= 0;
foreach (new RecursiveIteratorIterator($ph, RecursiveIteratorIterator::SELF_FIRST) as $f) {
fe_more_time();
$name= substr($f->getPathname(), strlen('phar://'.str_replace('\\', '/', $file)) + 1);
if ($f->isFile()) { $n++; $sum+= $f->getSize(); }
if (count($rows) < 300) $rows[]= str_pad($f->isFile() ? html_entity_decode(p2h_nice_filesize($f->getSize())) : '', 10, ' ', STR_PAD_LEFT).' '.$name.($f->isDir() ? '/' : '');
}
return $n.' '.lang('@files').', '.html_entity_decode(p2h_nice_filesize($sum)).' '.lang('@unpacked')."\n".implode("\n", $rows);
} catch (Exception $e) { }
}
if ($ext === 'gz' && function_exists('gzopen') && ($g= @gzopen($file, 'rb'))) {
$data= (string)gzread($g, 16384); gzclose($g);
return strpos($data, "\0") !== false ? fe_hexdump(substr($data, 0, 512)) : fe_utf8($data, strlen($data) >= 16384);
}
return null;
}
if ($kind === 'zip' || $kind === 'doc') {
if (!class_exists('ZipArchive')) return null;
$z= new ZipArchive();
if ($z->open($file, ZipArchive::RDONLY) !== true) return null;
if ($kind === 'zip') {
$n= $z->numFiles; $sum= 0; $rows= [];
for ($i= 0; $i < $n; $i++) {
$st= $z->statIndex($i); $sum+= $st['size'];
if ($i < 300) $rows[]= str_pad(substr($st['name'], -1) === '/' ? '' : html_entity_decode(p2h_nice_filesize($st['size'])), 10, ' ', STR_PAD_LEFT).' '.$st['name'];
}
$z->close();
return $n.' '.lang('@files').', '.html_entity_decode(p2h_nice_filesize($sum)).' '.lang('@unpacked')."\n".implode("\n", $rows);
}
$txt= '';
if ($ext === 'pptx') { // The text of each slide
$sl= [];
for ($i= 0; $i < $z->numFiles; $i++) if (preg_match('#^ppt/slides/slide(\d+)\.xml$#', $z->getNameIndex($i), $m)) $sl[(int)$m[1]]= $z->getNameIndex($i);
ksort($sl);
foreach ($sl as $no => $part) { $txt.= '--- '.$no." ---\n".fe_xml_text((string)$z->getFromName($part))."\n\n"; if (strlen($txt) > 16384) break; }
} elseif ($ext === 'epub') { // The text of the chapters, in the order of their names
$ch= [];
$opf= preg_match('#full-path="([^"]+)"#', (string)$z->getFromName('META-INF/container.xml'), $om) ? html_entity_decode($om[1], ENT_QUOTES | ENT_XML1, 'UTF-8') : '';
$pkg= $opf > '' ? (string)$z->getFromName($opf) : '';
if ($pkg > '') { // The reading order: the spine of the package file
$dir= strpos($opf, '/') !== false ? substr($opf, 0, strrpos($opf, '/') + 1) : ''; $man= [];
if (preg_match_all('#<(?:\w+:)?item\b[^>]*>#', $pkg, $im))
foreach ($im[0] as $tag)
if (preg_match('#\bid="([^"]+)"#', $tag, $a) && preg_match('~\bhref="([^"#]+)~', $tag, $h)) $man[$a[1]]= $dir.rawurldecode(html_entity_decode($h[1], ENT_QUOTES | ENT_XML1, 'UTF-8'));
if (preg_match_all('#<(?:\w+:)?itemref\b[^>]*\bidref="([^"]+)"#', $pkg, $sp))
foreach ($sp[1] as $id) if (isset($man[$id]) && $z->locateName($man[$id]) !== false) $ch[]= $man[$id];
}
if (!$ch) { // No spine: the order of the names
for ($i= 0; $i < $z->numFiles; $i++) if (preg_match('#\.x?html?$#i', $z->getNameIndex($i))) $ch[]= $z->getNameIndex($i);
natsort($ch);
}
foreach ($ch as $part) { $txt.= fe_xml_text(preg_replace('#<head.*?</head>#is', '', (string)$z->getFromName($part)))."\n\n"; if (strlen($txt) > 16384) break; }
} else { // docx - odt / odp
$xml= $z->getFromName('word/document.xml');
if ($xml === false) $xml= $z->getFromName('content.xml');
if ($xml !== false) $txt= fe_xml_text($xml);
}
$z->close();
return $txt === '' ? null : substr(trim($txt), 0, 16384);
}
$raw= (string)file_get_contents($file, false, null, 0, 16384);
$txt= fe_bom($raw); // UTF-16 (Windows) and byte order marks
if (strpos($txt, "\0") !== false) return fe_hexdump(substr($raw, 0, 512), $file); // A binary file: its first bytes
return fe_utf8($txt, strlen($txt) >= 16384);
}
function fe_preview_table($file) { // The first rows of a table: CSV / TSV, Excel (xlsx) or Calc (ods) - ['rows' => [[cells]], 'more' => bool, 'sheet' => name]
$ext= strtolower(pathinfo($file, PATHINFO_EXTENSION));
$max= 40; $cols= 30; $rows= []; $more= false; $sheet= '';
$cell= function($v) { $v= trim((string)$v); return mb_strlen($v) > 120 ? mb_substr($v, 0, 120).'…' : $v; };
if ($ext === 'csv' || $ext === 'tsv') {
$data= fe_bom((string)@file_get_contents($file, false, null, 0, 262144));
if (!preg_match('//u', $data)) $data= fe_utf8($data, strlen($data) >= 262144); // Windows-1252 (or a character cut at the end)
$h= fopen('php://memory', 'w+b'); fwrite($h, $data); rewind($h);
$first= (string)fgets($h, 65536); rewind($h);
$sep= $ext === 'tsv' ? "\t" : (substr_count($first, ';') > substr_count($first, ',') ? ';' : (substr_count($first, "\t") > substr_count($first, ',') ? "\t" : ','));
while (($r= fgetcsv($h, 65536, $sep, '"', '')) !== false) {
if (count($rows) >= $max) { $more= true; break; }
$rows[]= array_map($cell, array_slice($r, 0, $cols));
}
fclose($h);
return ['rows' => $rows, 'more' => $more, 'sheet' => ''];
}
if (!class_exists('XMLReader') || !class_exists('ZipArchive')) return null;
$z= new ZipArchive();
if ($z->open($file, ZipArchive::RDONLY) !== true) return null;
$zp= 'zip://'.str_replace('\\', '/', $file).'#';
if ($ext === 'xlsx') {
$shared= []; // The shared strings (at most 20000)
if ($z->locateName('xl/sharedStrings.xml') !== false) {
$xr= new XMLReader();
if (@$xr->open($zp.'xl/sharedStrings.xml')) {
while ($xr->read() && count($shared) < 20000)
if ($xr->nodeType === XMLReader::ELEMENT && $xr->localName === 'si')
$shared[]= html_entity_decode(strip_tags(preg_replace('#<rPh\b.*?</rPh>#s', '', $xr->readInnerXml())), ENT_QUOTES | ENT_XML1, 'UTF-8'); // (no phonetic guide)
$xr->close();
}
}
$wb= (string)$z->getFromName('xl/workbook.xml');
$part= 'xl/worksheets/sheet1.xml';
if (preg_match('#<sheet [^>]*>#', $wb, $sm)) { // The first sheet of the workbook - through its relation (it need not be sheet1.xml)
if (preg_match('#name="([^"]*)"#', $sm[0], $m)) $sheet= html_entity_decode($m[1], ENT_QUOTES | ENT_XML1, 'UTF-8');
if (preg_match('#r:id="([^"]*)"#', $sm[0], $m) && preg_match('#<Relationship [^>]*Id="'.preg_quote($m[1], '#').'"[^>]*>#', (string)$z->getFromName('xl/_rels/workbook.xml.rels'), $rm)
&& preg_match('#Target="([^"]*)"#', $rm[0], $tm)) {
$tg= ltrim(html_entity_decode($tm[1], ENT_QUOTES | ENT_XML1, 'UTF-8'), '/');
$tg= strpos($tg, 'xl/') === 0 ? $tg : 'xl/'.$tg;
if ($z->locateName($tg) !== false) $part= $tg;
}
}
if ($z->locateName($part) === false) for ($i= 0; $i < $z->numFiles; $i++) if (preg_match('#^xl/worksheets/[^/]+\.xml$#', $z->getNameIndex($i))) { $part= $z->getNameIndex($i); break; }
$base1904= (bool)preg_match('#<workbookPr [^>]*date1904="(1|true)"#', $wb); // Excel for Mac: days from 1904
$dateXf= []; // The cell styles that are dates (number formats 14-22, 45-47 or own formats with d / m / y)
$st= (string)$z->getFromName('xl/styles.xml');
$own= [];
if (preg_match_all('#<numFmt [^>]*numFmtId="(\d+)"[^>]*formatCode="([^"]*)"#', $st, $mm, PREG_SET_ORDER))
foreach ($mm as $f) $own[(int)$f[1]]= preg_match('/[dmy]/i', preg_replace('/"[^"]*"|\[[^\]]*\]/', '', html_entity_decode($f[2])));
if (preg_match('#<cellXfs[^>]*>(.*?)</cellXfs>#s', $st, $cx) && preg_match_all('#<xf\b([^>]*)>#', $cx[1], $xm))
foreach ($xm[1] as $k => $at) {
$id= preg_match('#numFmtId="(\d+)"#', $at, $im) ? (int)$im[1] : 0;
$dateXf[$k]= ($id >= 14 && $id <= 22) || ($id >= 45 && $id <= 47) || !empty($own[$id]);
}
$z->close();
$xr= new XMLReader();
if (!@$xr->open($zp.$part)) return null;
$row= null; $ci= 0; $t= ''; $rn= 0;
while ($xr->read()) {
if ($xr->nodeType === XMLReader::ELEMENT && $xr->localName === 'row') {
$no= (int)$xr->getAttribute('r') ?: $rn + 1;