-
Notifications
You must be signed in to change notification settings - Fork 351
/
filemanager.class.php
executable file
·1602 lines (1262 loc) · 52 KB
/
filemanager.class.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
/**
* Filemanager PHP class
*
* filemanager.class.php
* class for the filemanager.php connector
*
* @license MIT License
* @author Riaan Los <mail (at) riaanlos (dot) nl>
* @author Simon Georget <simon (at) linea21 (dot) com>
* @copyright Authors
*/
class Filemanager {
protected $config = array();
protected $language = array();
protected $get = array();
protected $post = array();
protected $properties = array();
protected $item = array();
protected $languages = array();
protected $allowed_actions = array();
protected $root = ''; // Filemanager root folder
protected $doc_root = ''; // root folder known by JS : $this->config['options']['fileRoot'] (filepath or '/') or $_SERVER['DOCUMENT_ROOT'] - overwritten by setFileRoot() method
protected $dynamic_fileroot = ''; // Only set if setFileRoot() is called. Second part of the path : '/Filemanager/assets/' ( doc_root - $_SERVER['DOCUMENT_ROOT'])
protected $path_to_files = ''; // path to FM userfiles folder - automatically computed by the PHP class, something like '/var/www/Filemanager/userfiles'
protected $logger = false;
protected $logfile = '';
protected $cachefolder = '_thumbs/';
protected $thumbnail_width = 64;
protected $thumbnail_height = 64;
protected $separator = 'userfiles'; // @todo fix keep it or not?
public function __construct($extraConfig = '') {
// getting default config file
$content = file_get_contents("../../scripts/filemanager.config.default.json");
$config_default = json_decode($content, true);
// getting user config file
if(isset($_REQUEST['config'])) {
$this->getvar('config');
if (file_exists("../../scripts/" . $_REQUEST['config'])) {
$this->__log('Loading ' . basename($this->get['config']) . ' config file.');
$content = file_get_contents("../../scripts/" . basename($this->get['config']));
} else {
$this->__log($this->get['config'] . ' config file does not exists.');
$this->error("Given config file (".basename($this->get['config']).") does not exist !");
}
} else {
$content = file_get_contents("../../scripts/filemanager.config.json");
}
$config = json_decode($content, true);
// setting encoding to prevent bug https://github.com/simogeo/Filemanager/issues/474#issuecomment-214781921
if(!isset($this->config['system']['locale']))
setlocale(LC_ALL, 'en_US.UTF-8');
else
setlocale(LC_ALL, $this->config['system']['locale']);
// setting timezone to prevent bug https://github.com/simogeo/Filemanager/issues/382#issuecomment-252472891
if(!isset($this->config['system']['timezone']))
date_default_timezone_set('UTC');
else
date_default_timezone_set($this->config['system']['timezone']);
// Prevent following bug https://github.com/simogeo/Filemanager/issues/398
$config_default['security']['uploadRestrictions'] = array();
if(!$config) {
$this->error("Error parsing the settings file! Please check your JSON syntax.");
}
$this->config = array_replace_recursive ($config_default, $config);
// override config options if needed
if(!empty($extraConfig)) {
$this->setup($extraConfig);
}
// set logfile path according to system if not set into config file
if(!isset($this->config['options']['logfile']))
$this->config['options']['logfile'] = sys_get_temp_dir(). '/filemanager.log';
$this->root = dirname(dirname(dirname(__FILE__))).DIRECTORY_SEPARATOR;
$this->properties = array(
'Date Created'=>null,
'Date Modified'=>null,
'Height'=>null,
'Width'=>null,
'Size'=>null
);
// Log actions or not?
if ($this->config['options']['logger'] == true ) {
if(isset($this->config['options']['logfile'])) {
$this->logfile = $this->config['options']['logfile'];
}
$this->enableLog();
}
// if fileRoot is set manually, $this->doc_root takes fileRoot value
// for security check in is_valid_path() method
// else it takes $_SERVER['DOCUMENT_ROOT'] default value
if ($this->config['options']['fileRoot'] !== false ) {
if($this->config['options']['serverRoot'] === true) {
$this->doc_root = $_SERVER['DOCUMENT_ROOT'];
$this->separator = basename($this->config['options']['fileRoot']);
$this->path_to_files = $_SERVER['DOCUMENT_ROOT'] .'/' . $this->config['options']['fileRoot'];
} else {
$this->doc_root = $this->config['options']['fileRoot'];
$this->separator = basename($this->config['options']['fileRoot']);
$this->path_to_files = $this->config['options']['fileRoot'];
}
} else {
$this->doc_root = $_SERVER['DOCUMENT_ROOT'];
$this->path_to_files = $this->root . $this->separator .'/' ;
}
$this->__log(__METHOD__ . ' $this->root value ' . $this->root);
$this->__log(__METHOD__ . ' $this->path_to_files ' . $this->path_to_files);
$this->__log(__METHOD__ . ' $this->doc_root value ' . $this->doc_root);
$this->__log(__METHOD__ . ' $this->separator value ' . $this->separator);
$this->setParams();
$this->setPermissions();
$this->availableLanguages();
$this->loadLanguageFile();
}
// $extraconfig should be formatted as json config array.
public function setup($extraconfig) {
// Prevent following bug https://github.com/simogeo/Filemanager/issues/398
$config_default['security']['uploadRestrictions'] = array();
$this->config = array_replace_recursive($this->config, $extraconfig);
}
// allow Filemanager to be used with dynamic folders
public function setFileRoot($path, $mkdir = false) {
// Paths are bit complex to handle - kind of nightmare actually ....
// 3 parts are availables
// [1] $this->doc_root. The first part of the path : '/var/www'
// [2] $this->dynamic_fileroot. The second part of the path : '/Filemanager/assets/' ( doc_root - $_SERVER['DOCUMENT_ROOT'])
// [3] $this->path_to_files or $this->doc_root. The full path : '/var/www/Filemanager/assets/'
$path = rtrim($path, '/') . '/';
if($this->config['options']['serverRoot'] === true) {
$this->doc_root = $_SERVER['DOCUMENT_ROOT']. '/'. $path; // i.e '/var/www/'
} else {
$this->doc_root = $path; // i.e '/var/www/'
}
// necessary for retrieving path when set dynamically with $fm->setFileRoot() method
// https://github.com/simogeo/Filemanager/issues/258 @todo to explore deeper
$this->dynamic_fileroot = str_replace("//","/",str_replace($_SERVER['DOCUMENT_ROOT'], '', $this->doc_root));
$this->path_to_files = $this->doc_root;
$this->separator = basename($this->doc_root);
// do we create folder ?
if($mkdir && !file_exists($this->doc_root)) {
mkdir($this->doc_root, 0755, true);
$this->__log(__METHOD__ . ' creating ' . $this->doc_root. ' folder through mkdir()');
}
$this->__log(__METHOD__ . ' $this->doc_root value overwritten : ' . $this->doc_root);
$this->__log(__METHOD__ . ' $this->dynamic_fileroot value ' . $this->dynamic_fileroot);
$this->__log(__METHOD__ . ' $this->path_to_files ' . $this->path_to_files);
$this->__log(__METHOD__ . ' $this->separator value ' . $this->separator);
}
public function error($string,$textarea=false) {
$array = array(
'Error'=>$string,
'Code'=>'-1',
'Properties'=>$this->properties
);
$this->__log( __METHOD__ . ' - error message : ' . $string);
if($textarea) {
echo '<textarea>' . json_encode($array) . '</textarea>';
} else {
echo json_encode($array);
}
die();
}
public function lang($string) {
if(isset($this->language[$string]) && $this->language[$string]!='') {
return $this->language[$string];
} else {
return 'Language string error on ' . $string;
}
}
public function getvar($var, $sanitize = true) {
if(!isset($_GET[$var]) || $_GET[$var]=='') {
$this->error(sprintf($this->lang('INVALID_VAR'),$var));
} else {
if($sanitize) {
$this->get[$var] = $this->sanitize($_GET[$var]);
} else {
$this->get[$var] = $_GET[$var];
}
return true;
}
}
public function postvar($var, $sanitize = true) {
if(!isset($_POST[$var]) || ($var != 'content' && $_POST[$var]=='')) {
$this->error(sprintf($this->lang('INVALID_VAR'),$var));
} else {
if($sanitize) {
$this->post[$var] = $this->sanitize($_POST[$var]);
} else {
$this->post[$var] = $_POST[$var];
}
return true;
}
}
public function getinfo() {
$this->item = array();
$this->item['properties'] = $this->properties;
$this->get_file_info('', false);
// handle path when set dynamically with $fm->setFileRoot() method
if($this->dynamic_fileroot != '') {
$path = $this->dynamic_fileroot. $this->get['path'];
// $path = str_replace($_SERVER['DOCUMENT_ROOT'], '', $this->path_to_files) . $this->get['path']; // instruction could replace the line above
$path = preg_replace('~/+~', '/', $path); // remove multiple slashes
} else {
$path = $this->get['path'];
}
$array = array(
'Path'=> $path,
'Filename'=>$this->item['filename'],
'File Type'=>$this->item['filetype'],
'Protected'=>$this->item['protected'],
'Preview'=>$this->item['preview'],
'Properties'=>$this->item['properties'],
'Error'=>"",
'Code'=>0
);
return $array;
}
public function getfolder() {
$array = array();
$filesDir = array();
$current_path = $this->getFullPath();
if(!$this->is_valid_path($current_path)) {
$this->error("No way.");
}
if(!is_dir($current_path)) {
$this->error(sprintf($this->lang('DIRECTORY_NOT_EXIST'),$this->get['path']));
}
// check if file is readable
if(!$this->has_system_permission($current_path, array('r'))) {
$this->error(sprintf($this->lang('NOT_ALLOWED_SYSTEM')));
}
if(!$handle = @opendir($current_path)) {
$this->error(sprintf($this->lang('UNABLE_TO_OPEN_DIRECTORY'),$this->get['path']));
} else {
while (false !== ($file = readdir($handle))) {
if($file != "." && $file != "..") {
array_push($filesDir, $file);
}
}
closedir($handle);
// By default
// Sorting files by name ('default' or 'NAME_DESC' cases from $this->config['options']['fileSorting']
natcasesort($filesDir);
foreach($filesDir as $file) {
if(is_dir($current_path . $file)) {
if(!in_array($file, $this->config['exclude']['unallowed_dirs']) && !preg_match( $this->config['exclude']['unallowed_dirs_REGEXP'], $file)) {
// check if file is writable and readable
if(!$this->has_system_permission($current_path . $file, array('w', 'r'))) {
$protected = 1;
$previewPath = $this->config['icons']['path'] . 'locked_' . $this->config['icons']['directory'];
} else {
$protected =0;
$previewPath = $this->config['icons']['path'] . $this->config['icons']['directory'];
}
$array[$this->get['path'] . $file .'/'] = array(
'Path'=> $this->get['path'] . $file .'/',
'Filename'=>$file,
'File Type'=>'dir',
'Protected'=>$protected,
'Preview'=> $previewPath,
'Properties'=>array(
'Date Created'=> date($this->config['options']['dateFormat'], filectime($this->getFullPath($this->get['path'] . $file .'/'))),
'Date Modified'=> date($this->config['options']['dateFormat'], filemtime($this->getFullPath($this->get['path'] . $file .'/'))),
'filemtime'=> filemtime($this->getFullPath($this->get['path'] . $file .'/')),
'Height'=>null,
'Width'=>null,
'Size'=>null
),
'Error'=>"",
'Code'=>0
);
}
} else if (!in_array($file, $this->config['exclude']['unallowed_files']) && !preg_match( $this->config['exclude']['unallowed_files_REGEXP'], $file)) {
$this->item = array();
$this->item['properties'] = $this->properties;
$this->get_file_info($this->get['path'] . $file, true);
if(!isset($this->params['type']) || (isset($this->params['type']) && strtolower($this->params['type'])=='images' && in_array(strtolower($this->item['filetype']),array_map('strtolower', $this->config['images']['imagesExt'])))) {
if($this->config['upload']['imagesOnly']== false || ($this->config['upload']['imagesOnly']== true && in_array(strtolower($this->item['filetype']),array_map('strtolower', $this->config['images']['imagesExt'])))) {
$array[$this->get['path'] . $file] = array(
'Path'=>$this->get['path'] . $file,
'Filename'=>$this->item['filename'],
'File Type'=>$this->item['filetype'],
'Protected'=>$this->item['protected'],
'Preview'=>$this->item['preview'],
'Properties'=>$this->item['properties'],
'Error'=>"",
'Code'=>0
);
}
}
}
}
}
$array = $this->sortFiles($array);
return $array;
}
public function editfile() {
$current_path = $this->getFullPath();
// prevent editing .htaccess file
if(strpos($current_path, '.htaccess') !== false) $this->error("No way.");
// check if file is writable
if(!$this->has_system_permission($current_path, array('w'))) {
$this->error(sprintf($this->lang('NOT_ALLOWED_SYSTEM')));
}
if(!$this->has_permission('edit') || !$this->is_valid_path($current_path) || !$this->is_editable($current_path)) {
$this->error("No way.");
}
$this->__log(__METHOD__ . ' - editing file '. $current_path);
$content = file_get_contents($current_path);
$content = htmlspecialchars($content);
if($content === false) {
$this->error(sprintf($this->lang('ERROR_OPENING_FILE')));
}
$array = array(
'Error'=>"",
'Code'=>0,
'Path'=>$this->get['path'],
'Content'=>$this->formatPath($content)
);
return $array;
}
public function savefile() {
$current_path = $this->getFullPath($this->post['path']);
if(!$this->has_permission('edit') || !$this->is_valid_path($current_path) || !$this->is_editable($current_path)) {
$this->error("No way.");
}
if(!$this->has_system_permission($current_path, array('w'))) {
$this->error(sprintf($this->lang('ERROR_WRITING_PERM')));
}
$this->__log(__METHOD__ . ' - saving file '. $current_path);
$content = htmlspecialchars_decode($this->post['content']);
$r = file_put_contents($current_path, $content, LOCK_EX);
if(!is_numeric($r)) {
$this->error(sprintf($this->lang('ERROR_SAVING_FILE')));
}
$array = array(
'Error'=>"",
'Code'=>0,
'Path'=>$this->formatPath($this->post['path'])
);
return $array;
}
public function rename() {
$suffix='';
if(substr($this->get['old'],-1,1)=='/') {
$this->get['old'] = substr($this->get['old'],0,(strlen($this->get['old'])-1));
$suffix='/';
}
$tmp = explode('/',$this->get['old']);
$filename = $tmp[(sizeof($tmp)-1)];
$newPath = str_replace('/' . $filename, '', $this->get['old']);
$newName = $this->cleanString($this->get['new'], array('.', '-'));
$old_file = $this->getFullPath($this->get['old']) . $suffix;
$new_file = $this->getFullPath($newPath . '/' . $newName). $suffix;
if(!$this->has_permission('rename') || !$this->is_valid_path($old_file)) {
$this->error("No way.");
}
// prevent renaming .htaccess file
if(strpos($old_file, '.htaccess') !== false) $this->error("No way.");
// check if file is writable
if(!$this->has_system_permission($old_file, array('w'))) {
$this->error(sprintf($this->lang('NOT_ALLOWED_SYSTEM')));
}
// check if not requesting main FM userfiles folder
if($this->is_root_folder($old_file)) {
$this->error(sprintf($this->lang('NOT_ALLOWED')));
}
// For file only - we check if the new given extension is allowed regarding the security Policy settings
if(is_file($old_file)) {
if($this->config['security']['allowChangeExtensions'] == false && ($this->get_ext($old_file) != $this->get_ext($new_file))) $this->error(sprintf($this->lang('NOT_ALLOWED')));
if(!$this->is_allowed_file_type($new_file)) $this->error(sprintf($this->lang('INVALID_FILE_TYPE')));
}
$this->__log(__METHOD__ . ' - renaming '. $old_file. ' to ' . $new_file);
if(file_exists($new_file)) {
if($suffix == '/' && is_dir($new_file)) {
$this->error(sprintf($this->lang('DIRECTORY_ALREADY_EXISTS'), $newName));
}
if($suffix == '' && is_file($new_file)) {
$this->error(sprintf($this->lang('FILE_ALREADY_EXISTS'), $newName));
}
}
if(!rename($old_file,$new_file)) {
if(is_dir($old_file)) {
$this->error(sprintf($this->lang('ERROR_RENAMING_DIRECTORY'), $filename, $newName));
} else {
$this->error(sprintf($this->lang('ERROR_RENAMING_FILE'), $filename, $newName));
}
} else {
// For image only - rename thumbnail if original image was successfully renamed
if(!is_dir($new_file) && $this->is_image($new_file)) {
$new_thumbnail = $this->get_thumbnail_path($new_file);
$old_thumbnail = $this->get_thumbnail_path($old_file);
if(file_exists($old_thumbnail)) {
rename($old_thumbnail, $new_thumbnail);
}
}
}
$array = array(
'Error' => "",
'Code' => 0,
'Old Path' => $this->formatPath($this->get['old'] . $suffix),
'Old Name' => $filename,
'New Path' => $this->formatPath($newPath . '/' . $newName . $suffix),
'New Name' => $newName
);
return $array;
}
public function move() {
// dynamic fileroot dir must be used when enabled
if($this->dynamic_fileroot != '') {
$rootDir = $this->dynamic_fileroot;
//$rootDir = str_replace($_SERVER['DOCUMENT_ROOT'], '', $this->path_to_files); // instruction could replace the line above
} else {
$rootDir = $this->get['root'];
}
$rootDir = str_replace('//', '/', $rootDir);
$oldPath = $this->getFullPath($this->get['old']);
// check if file is writable
if(!$this->has_system_permission($oldPath, array('w'))) {
$this->error(sprintf($this->lang('NOT_ALLOWED_SYSTEM')),true);
}
// check if not requesting main FM userfiles folder
if($this->is_root_folder($oldPath)) {
$this->error(sprintf($this->lang('NOT_ALLOWED')),true);
}
// old path
$tmp = explode('/',trim($this->get['old'], '/'));
$fileName = array_pop($tmp); // file name or new dir name
$path = '/' . implode('/', $tmp) . '/';
// new path
if (substr($this->get['new'], 0, 1) != "/") {
// make path relative from old dir
$newPath = $path . '/' . $this->get['new'] . '/';
} else {
$newPath = $rootDir . '/' . $this->get['new'] . '/';
}
$newPath = preg_replace('#/+#', '/', $newPath);
$newPath = $this->expandPath($newPath, true);
$newRelativePath = str_replace('./', '',$newPath);
$newPath = $this->getFullPath($newPath);
if(!$this->has_permission('move') || !$this->is_valid_path($oldPath) || !$this->is_valid_path($newPath)) {
$this->error("No way.");
}
// prevent moving .htaccess file
if(strpos($oldPath, '.htaccess') !== false) $this->error("No way.");
// check if file already exists
if (file_exists($newPath.$fileName)) {
if(is_dir($newPath.$fileName)) {
$this->error(sprintf($this->lang('DIRECTORY_ALREADY_EXISTS'),rtrim($this->get['new'], '/').'/'.$fileName));
} else {
$this->error(sprintf($this->lang('FILE_ALREADY_EXISTS'),rtrim($this->get['new'], '/').'/'.$fileName));
}
}
// create dir if not exists
if (!file_exists($newPath)) {
if(!mkdir($newPath,0755, true)) {
$this->error(sprintf($this->lang('UNABLE_TO_CREATE_DIRECTORY'),$newPath));
}
}
// move
$this->__log(__METHOD__ . ' - moving '. $oldPath. ' to directory ' . $newPath);
if(!rename($oldPath,$newPath . $fileName)) {
if(is_dir($oldPath)) {
$this->error(sprintf($this->lang('ERROR_RENAMING_DIRECTORY'),$path,$this->get['new']));
} else {
$this->error(sprintf($this->lang('ERROR_RENAMING_FILE'),$path . $fileName,$this->get['new']));
}
}
$array = array(
'Error'=>"",
'Code'=>0,
'Old Path'=>$path,
'Old Name'=>$fileName,
'New Path'=>$this->formatPath($newRelativePath),
'New Name'=>$fileName,
);
return $array;
}
public function delete() {
$current_path = $this->getFullPath();
$thumbnail_path = $this->get_thumbnail_path($current_path);
if(!$this->has_permission('delete') || !$this->is_valid_path($current_path)) {
$this->error("No way.");
}
// prevent deleting .htaccess file
if(strpos($current_path, '.htaccess') !== false) $this->error("No way.");
// check if file is writable
if(!$this->has_system_permission($current_path, array('w'))) {
$this->error(sprintf($this->lang('NOT_ALLOWED_SYSTEM')));
}
// check if not requesting main FM userfiles folder
if($this->is_root_folder($current_path)) {
$this->error(sprintf($this->lang('NOT_ALLOWED')));
}
if(is_dir($current_path)) {
$this->unlinkRecursive($current_path);
// we remove thumbnails if needed
$this->__log(__METHOD__ . ' - deleting thumbnails folder '. $thumbnail_path);
$this->unlinkRecursive($thumbnail_path);
$array = array(
'Error'=>"",
'Code'=>0,
'Path'=>$this->formatPath($this->get['path'])
);
$this->__log(__METHOD__ . ' - deleting folder '. $current_path);
return $array;
} else if(file_exists($current_path)) {
unlink($current_path);
// delete thumbail if exists
$this->__log(__METHOD__ . ' - deleting thumbnail file '. $thumbnail_path);
if(file_exists($thumbnail_path)) unlink($thumbnail_path);
$array = array(
'Error'=>"",
'Code'=>0,
'Path'=>$this->formatPath($this->get['path'])
);
$this->__log(__METHOD__ . ' - deleting file '. $current_path);
return $array;
} else {
$this->error(sprintf($this->lang('INVALID_DIRECTORY_OR_FILE')));
}
}
public function replace() {
$this->setParams();
if(!isset($_FILES['fileR']) || !is_uploaded_file($_FILES['fileR']['tmp_name'])) {
// if fileSize limit set by the user is greater than size allowed in php.ini file, we apply server restrictions
// and log a warning into file
if($this->config['upload']['fileSizeLimit'] > $this->getMaxUploadFileSize()) {
$this->__log(__METHOD__ . ' [WARNING] : file size limit set by user is greater than size allowed in php.ini file : '. $this->config['upload']['fileSizeLimit']. $this->lang('mb') .' > '. $this->getMaxUploadFileSize(). $this->lang('mb'). '.');
$this->config['upload']['fileSizeLimit'] = $this->getMaxUploadFileSize();
$this->error(sprintf($this->lang('UPLOAD_FILES_SMALLER_THAN'),$this->config['upload']['fileSizeLimit'] . $this->lang('mb')),true);
}
$this->error(sprintf($this->lang('INVALID_FILE_UPLOAD') . ' '. sprintf($this->lang('UPLOAD_FILES_SMALLER_THAN'),$this->config['upload']['fileSizeLimit'] . $this->lang('mb'))),true);
}
// we determine max upload size if not set
if($this->config['upload']['fileSizeLimit'] == 'auto') {
$this->config['upload']['fileSizeLimit'] = $this->getMaxUploadFileSize();
}
if($_FILES['fileR']['size'] > ($this->config['upload']['fileSizeLimit'] * 1024 * 1024)) {
$this->error(sprintf($this->lang('UPLOAD_FILES_SMALLER_THAN'),$this->config['upload']['fileSizeLimit'] . $this->lang('mb')),true);
}
// we check the given file has the same extension as the old one
if(strtolower(pathinfo($_FILES['fileR']['name'], PATHINFO_EXTENSION)) != strtolower(pathinfo($this->post['newfilepath'], PATHINFO_EXTENSION))) {
$this->error(sprintf($this->lang('ERROR_REPLACING_FILE') . ' '. pathinfo($this->post['newfilepath'], PATHINFO_EXTENSION)),true);
}
if(!$this->is_allowed_file_type($_FILES['fileR']['name'])) {
$this->error(sprintf($this->lang('INVALID_FILE_TYPE')),true);
}
// we check if extension is allowed regarding the security Policy settings
if(!$this->is_allowed_file_type($_FILES['fileR']['name'])) {
$this->error(sprintf($this->lang('INVALID_FILE_TYPE')),true);
}
// we check if only images are allowed
if($this->config['upload']['imagesOnly'] || (isset($this->params['type']) && strtolower($this->params['type'])=='images')) {
if(!($size = @getimagesize($_FILES['fileR']['tmp_name']))){
$this->error(sprintf($this->lang('UPLOAD_IMAGES_ONLY')),true);
}
if(!in_array($size[2], array(1, 2, 3, 7, 8))) {
$this->error(sprintf($this->lang('UPLOAD_IMAGES_TYPE_JPEG_GIF_PNG')),true);
}
}
$current_path = $this->getFullPath($this->post['newfilepath']);
// check if file is writable
if(!$this->has_system_permission($current_path, array('w'))) {
$this->error(sprintf($this->lang('NOT_ALLOWED_SYSTEM')), true);
}
if(!$this->has_permission('replace') || !$this->is_valid_path($current_path)) {
$this->error("No way.");
}
move_uploaded_file($_FILES['fileR']['tmp_name'], $current_path);
// we delete thumbnail if file is image and thumbnail already
if($this->is_image($current_path) && file_exists($this->get_thumbnail($current_path))) {
unlink($this->get_thumbnail($current_path));
}
// automatically resize image if it's too big
$imagePath = $current_path;
if($this->is_image($imagePath) && $this->config['images']['resize']['enabled']) {
if ($size = @getimagesize($imagePath)){
if ($size[0] > $this->config['images']['resize']['maxWidth'] || $size[1] > $this->config['images']['resize']['maxHeight']) {
require_once('./inc/wideimage/lib/WideImage.php');
$image = WideImage::load($imagePath);
$resized = $image->resize($this->config['images']['resize']['maxWidth'], $this->config['images']['resize']['maxHeight'], 'inside');
$resized->saveToFile($imagePath);
$this->__log(__METHOD__ . ' - resizing image : '. $current_path);
}
}
}
chmod($current_path, 0644);
$response = array(
'Path'=>dirname($this->post['newfilepath']),
'Name'=>basename($this->post['newfilepath']),
'Error'=>"",
'Code'=>0
);
$this->__log(__METHOD__ . ' - replacing file '. $current_path);
echo '<textarea>' . json_encode($response) . '</textarea>';
die();
}
public function add() {
$this->setParams();
if(!isset($_FILES['newfile']) || !is_uploaded_file($_FILES['newfile']['tmp_name'])) {
// if fileSize limit set by the user is greater than size allowed in php.ini file, we apply server restrictions
// and log a warning into file
if($this->config['upload']['fileSizeLimit'] > $this->getMaxUploadFileSize()) {
$this->__log(__METHOD__ . ' [WARNING] : file size limit set by user is greater than size allowed in php.ini file : '. $this->config['upload']['fileSizeLimit'] . 'Mb > '. $this->getMaxUploadFileSize() .'Mb.');
$this->config['upload']['fileSizeLimit'] = $this->getMaxUploadFileSize();
$this->error(sprintf($this->lang('UPLOAD_FILES_SMALLER_THAN'),$this->config['upload']['fileSizeLimit'] . $this->lang('mb')),true);
}
$this->error(sprintf($this->lang('INVALID_FILE_UPLOAD') . ' '. sprintf($this->lang('UPLOAD_FILES_SMALLER_THAN'),$this->config['upload']['fileSizeLimit'] . $this->lang('mb'))),true);
}
// we determine max upload size if not set
if($this->config['upload']['fileSizeLimit'] == 'auto') {
$this->config['upload']['fileSizeLimit'] = $this->getMaxUploadFileSize();
}
if($_FILES['newfile']['size'] > ($this->config['upload']['fileSizeLimit'] * 1024 * 1024)) {
$this->error(sprintf($this->lang('UPLOAD_FILES_SMALLER_THAN'),$this->config['upload']['fileSizeLimit'] . $this->lang('mb')),true);
}
// we check if extension is allowed regarding the security Policy settings
if(!$this->is_allowed_file_type($_FILES['newfile']['name'])) {
$this->error(sprintf($this->lang('INVALID_FILE_TYPE')),true);
}
// we check if only images are allowed
if($this->config['upload']['imagesOnly'] || (isset($this->params['type']) && strtolower($this->params['type'])=='images')) {
if(!($size = @getimagesize($_FILES['newfile']['tmp_name']))){
$this->error(sprintf($this->lang('UPLOAD_IMAGES_ONLY')),true);
}
if(!in_array($size[2], array(1, 2, 3, 7, 8))) {
$this->error(sprintf($this->lang('UPLOAD_IMAGES_TYPE_JPEG_GIF_PNG')),true);
}
}
$_FILES['newfile']['name'] = $this->cleanString($_FILES['newfile']['name'],array('.','-'));
$current_path = $this->getFullPath($this->post['currentpath']);
if(!$this->is_valid_path($current_path)) {
$this->error("No way.");
}
if(!$this->config['upload']['overwrite']) {
$_FILES['newfile']['name'] = $this->checkFilename($current_path,$_FILES['newfile']['name']);
}
move_uploaded_file($_FILES['newfile']['tmp_name'], $current_path . $_FILES['newfile']['name']);
// automatically resize image if it's too big
$imagePath = $current_path . $_FILES['newfile']['name'];
if($this->is_image($imagePath) && $this->config['images']['resize']['enabled']) {
if ($size = @getimagesize($imagePath)){
if ($size[0] > $this->config['images']['resize']['maxWidth'] || $size[1] > $this->config['images']['resize']['maxHeight']) {
require_once('./inc/wideimage/lib/WideImage.php');
$image = WideImage::load($imagePath);
$resized = $image->resize($this->config['images']['resize']['maxWidth'], $this->config['images']['resize']['maxHeight'], 'inside');
$resized->saveToFile($imagePath);
$this->__log(__METHOD__ . ' - resizing image : '. $_FILES['newfile']['name']. ' into '. $current_path);
}
}
}
chmod($current_path . $_FILES['newfile']['name'], 0644);
$response = array(
'Path'=>$this->post['currentpath'],
'Name'=>$_FILES['newfile']['name'],
'Error'=>"",
'Code'=>0
);
$this->__log(__METHOD__ . ' - adding file '. $_FILES['newfile']['name']. ' into '. $current_path);
echo '<textarea>' . json_encode($response) . '</textarea>';
die();
}
public function addfolder() {
$current_path = $this->getFullPath();
if(!$this->is_valid_path($current_path)) {
$this->error("No way.");
}
if(is_dir($current_path . $this->get['name'])) {
$this->error(sprintf($this->lang('DIRECTORY_ALREADY_EXISTS'),$this->get['name']));
}
$newdir = $this->cleanString($this->get['name']);
if(!mkdir($current_path . $newdir,0755)) {
$this->error(sprintf($this->lang('UNABLE_TO_CREATE_DIRECTORY'),$newdir));
}
$array = array(
'Parent'=>$this->get['path'],
'Name'=>$this->get['name'],
'Error'=>"",
'Code'=>0
);
$this->__log(__METHOD__ . ' - adding folder '. $current_path . $newdir);
return $array;
}
/**
* function zipFile. Creates a zip file from source to destination
*
* @param string $source Source path for zip
* @param string $destination Destination path for zip
* @param string|boolean $flag OPTIONAL If true includes the folder also
* @return boolean
* @link http://stackoverflow.com/questions/17584869/zip-main-folder-with-sub-folder-inside
*/
public function zipFile($source, $destination, $flag = '')
{
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if($flag)
{
$flag = basename($source) . '/';
//$zip->addEmptyDir(basename($source) . '/');
}
if (is_dir($source) === true)
{
// add file to prevent empty archive error on download
$zip->addFromString('fm', "This archive has been generated by simogeo's Filemanager : https://github.com/simogeo/Filemanager/");
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file)
{
$file = str_replace('\\', '/', realpath($file));
if (is_dir($file) === true)
{
$zip->addEmptyDir(str_replace($source . '/', '', $flag.$file . '/'));
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $flag.$file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString($flag.basename($source), file_get_contents($source));
}
return $zip->close();
}
public function download() {
$current_path = $this->getFullPath();
if(!$this->has_permission('download') || !$this->is_valid_path($current_path)) {
$this->error("No way.");
}
// prevent downloading .htaccess file
if(strpos($current_path, '.htaccess') !== false) $this->error("No way.");
// check if file is writable
if(!$this->has_system_permission($current_path, array('w'))) {
$this->error(sprintf($this->lang('NOT_ALLOWED_SYSTEM')),true);
}
// we check if extension is allowed regarding the security Policy settings
if(is_file($current_path)) {
if(!$this->is_allowed_file_type(basename($current_path))) {
$this->error(sprintf($this->lang('INVALID_FILE_TYPE')),true);
}
} else {
// check if permission is granted
if(is_dir($current_path) && $this->config['security']['allowFolderDownload'] == false ) {
$this->error(sprintf($this->lang('NOT_ALLOWED')),true);
}
// check if not requesting main FM userfiles folder
if($this->is_root_folder($current_path)) {
$this->error(sprintf($this->lang('NOT_ALLOWED')),true);
}
$destination_path = sys_get_temp_dir().'/'.uniqid().'.zip';
// if Zip archive is created
if($this->zipFile($current_path, $destination_path, true)) {
$current_path = $destination_path;
} else {
$this->error($this->lang('ERROR_CREATING_ZIP'));
}
}
if(isset($this->get['path']) && file_exists($current_path)) {
header("Content-type: application/force-download");
header('Content-Disposition: inline; filename="' . basename($current_path) . '"');
header("Content-Transfer-Encoding: Binary");
header("Content-length: ".filesize($current_path));
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($current_path) . '"');
readfile($current_path);
$this->__log(__METHOD__ . ' - downloading '. $current_path);
exit();
} else {
$this->error(sprintf($this->lang('FILE_DOES_NOT_EXIST'),$current_path));
}
}
public function preview($thumbnail) {
$current_path = $this->getFullPath();
if(!$this->is_valid_path($current_path)) $this->error("No way.");
if(isset($this->get['path']) && file_exists($current_path)) {
// if $thumbnail is set to true we return the thumbnail
if($this->config['options']['generateThumbnails'] == true && $thumbnail == true) {
// get thumbnail (and create it if needed)
$returned_path = $this->get_thumbnail($current_path);
} else {
$returned_path = $current_path;
}
header("Content-type: image/" . strtolower(pathinfo($returned_path, PATHINFO_EXTENSION)));
header("Content-Transfer-Encoding: Binary");
header("Content-length: ".filesize($returned_path));
header('Content-Disposition: inline; filename="' . basename($returned_path) . '"');
readfile($returned_path);
exit();
} else {
$this->error(sprintf($this->lang('FILE_DOES_NOT_EXIST'),$current_path));
}
}
public function getMaxUploadFileSize() {
$max_upload = (int) ini_get('upload_max_filesize');
$max_post = (int) ini_get('post_max_size');
$memory_limit = (int) ini_get('memory_limit');
$upload_mb = min($max_upload, $max_post, $memory_limit);